Polypus Inter-Layer Contracts¶
This document is the single source of truth for the agreements between Polypus
layers. The 2026-07 technical audit showed that every critical defect lived at
a seam between layers — not inside a module — so these contracts get their own
document, their own code owners (see CODEOWNERS), and their own tests.
Rules of the road:
- Changing a contract requires changing this file in the same PR, plus the
contract test that enforces it. A PR that alters a signature, kwarg, format
or gate set listed here without touching
docs/CONTRACTS.mdmust be rejected in review. - Each contract lists its enforcing test. "No test yet" is a temporary state, not an accepted one — the status table below tracks which are real.
- This file is deliberately public: it is equally useful to external contributors and to AI coding assistants working on a clone of this repo.
Status at a glance¶
| Contract | Seam | Enforcing test | Status | Known break (audit) |
|---|---|---|---|---|
| C-1 | Rust → Python execution | tests/python/test_seam_contract.py (+ test_memory_budget.py, test_cunqa_contract.py) |
✅ present | the CUNQA seal sent cores to qraise, which CUNQA renamed cores_per_qpu in 2.4.0, so every reservation raised TypeError on CUNQA ≥ 2.4 (#204, fixed: cores_per_qpu goes through unchanged; CUNQA 2.3 is no longer supported); disconnect now forwards family to qdrop (C1 fixed); local run_qcs received backend and id and CUNQA run_qcs received backend, none of them read (LOCAL-2, #230, fixed: Rust no longer sends them); Qiskit exceptions escaped the polypus hierarchy, now polypus.BackendError on the seam and polypus.EvaluationError when preparing/binding Qiskit circuits, with __cause__ (#218, fixed); a statevector too large for the memory limit was started and OOM-killed with no Python exception (#215, fixed: InsufficientMemoryError) |
| C-2 | Gate vocabulary symmetry | polypus-circuit + polypus-sim tests/contracts.rs (+ both crates' tests/inverse.rs for ConcreteCircuit::inverse; tests/python/test_local_aer_lowering.py and test_cunqa_lowering.py for the Aer and CUNQA lowerings; polypus-qml's every_instruction_kind_is_classified in src/problem.rs for the gradient's gate classification; polypus-sim's apply_inverse_undoes_every_instruction_kind in src/statevector.rs, every_generator_is_the_derivative_of_the_simulated_matrix in src/adjoint.rs (the table of generators) and every_instruction_kind_is_differentiated_through in tests/adjoint.rs for the adjoint gradient) |
✅ present | the OpenQASM 2.0 export rounded angles to 12 decimals, so a Clifford circuit stopped being Clifford to Aer, which simulated it with a statevector instead of the stabilizer method (fixed: shortest round-trip angles); the Aer lowering ran the full transpile against Aer's target, whose layout stage rejected circuits wider than the target's qubit count (derived from the host memory) even on the stabilizer method (fixed: synthesis and translation only, same circuit) |
| C-3 | Measurement counts format | shot-conservation + key order + last-write-wins | ✅ present | shots dropped on uneven distribution (C6); the native polypus backend OR-ed repeated writes to one classical bit instead of letting the last win (#205, fixed); RunResult.counts was a list[dict] for one QPU but a merged dict for n_qpus > 1, so result.counts[0] raised KeyError (#211, fixed); Aer raised QiskitError: No counts for a circuit without measurements instead of the full-register read-out (#218, fixed); CUNQA 3.0.0 failed such a job (key 'counts' not found) and split the key of a circuit with several classical registers with spaces (#253, #304, fixed in the seal); a measured OpenQASM program whose creg is wider than its highest written bit got keys as wide as the declared clbits on Aer but max(cbit)+1 on native (#251, fixed: the declared width on both); the same program imported as a polypus.Circuit lost the declared width at parameter binding and at export, so it got max(cbit)+1 on both (fixed: kept through both) |
| C-4 | Terminal measurement placement | polypus-circuit + polypus-sim tests/contracts.rs |
✅ present | — |
| C-5 | Optimizer ↔ oracle | invariant test, multi-seed + tests/python/test_oracle_contract.py (+ crates/polypus-optimizers/tests/initial_point.rs and tests/python/test_initial_point.py for initial_point, tests/python/test_final_shots.py for final_shots, and tests/python/test_qml_native_initial_point_final_shots.py for both through qml.Model.fit; crates/polypus-optimizers/tests/observer.rs and tests/python/test_callback.py for callback) |
✅ present | DE best_fitness mismatch (C4) |
| C-6 | Version coherence | release.yml gate (tag, internal pins, CHANGELOG.md, CITATION.cff ↔ Cargo.toml) + hygiene.yml (Cargo.toml ↔ CITATION.cff, pins) + tests/python/test_version_coherence.py (polypus.__version__ ↔ Cargo.toml ↔ installed distribution) |
✅ present | tag/Cargo diverged at 0.6.0 |
| C-7 | Seeding & run manifest | tests/python/test_seed_reproducibility.py (+ test_qml_predict.py, test_seed_range.py) + bindings/native Rust tests |
✅ present | repeated runs byte-identical / train seed hardcoded None (#34); an unreadable OS entropy source panicked while drawing a default seed (#249) or the run id's UUID (#264); both fixed: polypus.BackendError; on Aer about half of the drawn seeds, and any explicit one, of 2**63 or more reached Aer masked to 63 bits, so the reported seed was not the one Aer used (#393, fixed: drawn below 2**63, an explicit one raises polypus.ConfigurationError) |
| C-8 | qml.train row/dimension/label symmetry | tests/python/test_qml_train_validation.py (+ test_qml_supervised.py, test_qml_predict.py) |
✅ present | silent row truncation / late Qiskit error (#79) |
| C-9 | id charset (train/qml.train; Python mirror in running_functions) |
tests/python/test_id_validation.py, tests/python/test_python_helpers_hygiene.py |
✅ present | unvalidated id reached SLURM family_name / temp files / log streams (#89) |
| C-10 | OpenQASM 3 profile | polypus-circuit tests/qasm3.rs + polypus-sim tests/qasm3_semantics.rs + tests/python/test_qasm3*.py + fuzz/fuzz_targets/from_qasm3.rs |
✅ present | — |
| C-11 | Native QML (problem ↔ oracle, expectation Jacobian, quantum kernel, polypus.qml.Model, qml.expval/qml.jacobian/qml.vjp, qml.kernel_matrix, polypus.torch.QuantumLayer) |
polypus-qml tests/contracts.rs + tests/gradient_exactness.rs + tests/jacobian.rs + tests/adjoint.rs + tests/kernel.rs + src/kernel.rs + src/model.rs serde tests + polypus-sim tests/adjoint.rs + polypus-infrastructure native.rs adjoint and fidelity tests + polypus-evaluation qml_oracle.rs + the primitive tests in crates/polypus/src/bindings/qml.rs + tests/python/test_qml_native*.py + tests/python/test_qml_adjoint.py + tests/python/test_torch_*.py |
✅ present | the parameter-shift gradient was wrong for parameters shared across gates (convolution, pooling) until it shifted each occurrence (found when the native QML was brought onto main) |
| C-12 | Call trace (trace= / POLYPUS_CALL_TRACE, JSON Lines v1) |
polypus-orchestration src/trace.rs, src/trace/decorators.rs, src/flow/trace_tests.rs, tests/conformance_with_trace.rs + polypus src/bindings/call_trace.rs + tests/python/test_call_trace*.py (+ tests/python/test_interrupt.py test_trace_on_interrupt for Ctrl+C, and tests/python/test_typing_stubs.py TestTraceType for the stub type and the guide's example) |
✅ present | — |
✅ means the listed test enforces the contract; a ⏳ contract would be specified but only review-enforced until its test lands (none today). Known breaks link their issue where one was filed.
C-1 · Rust → Python execution seam (polypus_python)¶
The Rust infrastructure layer (crates/polypus-infrastructure/src/*.rs) calls
exactly three functions of the polypus_python package. Their names, argument
names and return shapes are frozen by this contract; the two sides must never
be changed independently.
connect_to_infrastructure(infrastructure: str, **kwargs)¶
infrastructure |
kwargs (exact names) | returns |
|---|---|---|
"local" |
— | the string "local" |
"cunqa" |
n: int (QPUs), t: str (SLURM walltime "HH:MM:SS"), n_nodes: int, family_name: str, cores_per_qpu: int |
CUNQA family handle (opaque object) |
t comes from the user-facing walltime kwarg (default "10:00:00"). The edge accepts only HH:MM:SS — HH one or more digits (48:00:00 is valid), MM and SS two digits below 60, total above zero; SLURM's D-HH:MM:SS is rejected — and raises ValueError before this call is made. local and qmio ignore it. tests/python/test_cunqa_walltime.py pins that the value arrives as t.
Every kwarg the Rust side sends must be consumed by the Python side;
silently ignoring one (as happened with cores_per_qpu) is a contract
violation.
The CUNQA seal translates these into cunqa.qpu.qraise(n, t, quantum_comm=False,
co_located=True, n_nodes=..., family=..., cores_per_qpu=...), plus backend
when POLYPUS_CUNQA_BACKEND is set. qraise has no **kwargs, so a name it
does not know raises TypeError. Supported CUNQA: >=2.4,<4. The argument
is cores_per_qpu from 2.4.0 (checked at 2.4.0, 3.0.0 and 3.1.0); CUNQA 2.3.0
spells it cores, so 2.3 is not supported and a reservation against it fails
with TypeError: qraise() got an unexpected keyword argument 'cores_per_qpu'.
tests/python/test_cunqa_contract.py binds the kwargs the seal sends against the
qraise, get_QPUs, run, gather and qdrop signatures extracted from those
four tags (tests/python/data/cunqa/, regenerated by extract_signatures.py).
It checks the call shapes only. tests/python/test_cunqa_run_flow.py drives
the whole run flow (run_quantum_circuit/train → CunqaBackend → seal) against
tests/python/fake_cunqa.py, a stateful fake bound to the same signatures that
simulates each job with Aer (#357). Neither has been run against a real CUNQA;
tests/python/test_cunqa_real.py is the opt-in test for a real family
(POLYPUS_CUNQA_REAL=1, never in CI).
family_name is the run id (RunParams::id, derived from ExecutionConfig::id
at backend construction), whose charset is constrained by C-9.
run_qcs(infrastructure: str, **kwargs)¶
| backend | kwargs (exact names) |
|---|---|
| local | qcs: list, shots: int, sim_method: str, max_parallel_experiments: int, noise_model (optional), seed: int (optional, C-7), max_memory_mb: int (optional, issue #215) |
| cunqa | family_id: str, qcs: list, shots: int, qpu_offset: int (C-7, issue #370), sim_method: str, seed: int (optional, C-7) |
max_memory_mb is sent by the local backend only when the memory budget is a
known limit (a valid POLYPUS_MEM_BUDGET, or the detected RAM/cgroup limit minus
the reserve) and is omitted for the blind fallback; it is the budget in whole MiB,
never 0 (which Aer reads as "no limit"). python/polypus_python/local.py consumes it by
passing it to AerSimulator(max_memory_mb=...), and passes nothing when it is
absent, so a direct caller keeps Aer's default. An experiment Aer then refuses for
lack of memory is raised as polypus.InsufficientMemoryError (see Failure modes).
qpu_offset is where the call's circuits start among the CUNQA family's QPUs:
circuit i runs on QPU qpu_offset + i. It is 0 except when a shot split
across the QPUs is uneven, which the Rust side sends as one call per batch size,
each with its first replica's index. The seal reads it with a default of 0.
family_id is the run id (RunParams::id, derived from
ExecutionConfig::id), whose charset is constrained by C-9; only CUNQA receives
it, as the name of the family to run on. The local seal receives no run id: it
creates nothing named after the run, and the id reaches the caller in
RunResult.id. Neither seal receives a backend kwarg: the local seal always
runs Aer's AerSimulator (the caller's backend="aer" / "polypus" choice is
resolved on the Rust side before any seam call), and CUNQA picks no simulator
class per job (the vQPU's is set at qraise, from POLYPUS_CUNQA_BACKEND).
tests/python/test_seam_contract.py pins the exact kwarg set each backend sends
and checks, by reading the seal's source, that Local.run_qcs and
Cunqa.run_qcs read every one of them. qcs elements are
either Qiskit QuantumCircuit objects or OpenQASM 2.0 strings; the Python side
parses strings (QuantumCircuit.from_qasm_str).
Returns list[dict[str, int]] — one dict per circuit, in submission
order (see C-3 for the dict format).
disconnect_from_infrastructure(infrastructure: str, **kwargs)¶
For "cunqa": single kwarg family (the handle returned by
connect_to_infrastructure), forwarded to CUNQA's qdrop. (Historical break,
audit C1, now fixed: the Python side used to read slurm_job_id — a key the
Rust side never sends — so a KeyError fired before qdrop ran and the QPU
allocation leaked. The Python side was corrected to read family; the Rust
side was already canonical.)
expectation_values(counts, fn) — no longer part of this seam¶
Historical: this was once the fourth seam function — the Rust layer handed the
counts back to Python to reduce them to expectation values. Expectation
computation is now native: polypus-observable evaluates declarative
QUBO/Ising costs, and polypus-evaluation's PyCallbackObservable calls a user
callback once per unique bitstring in a single GIL section and aggregates in
Rust. The Rust layer no longer calls expectation_values across the seam, so it
is not frozen by this contract. The function still lives in
python/polypus_python/qaoa_utils.py for Python-side use.
Failure modes (all three functions)¶
- An unknown
infrastructurevalue raisesValueError— never falls through to a default. - An unexpected kwarg raises
TypeError(the mirror of the "must-be-consumed" rule above: neither side silently drops or invents args). - A missing required kwarg raises
TypeError.
No backend binds parameters on this seam, so run_quantum_circuit rejects a
circuit with free parameters (a polypus.Circuit or a Qiskit QuantumCircuit)
with ValueError ("unbound parameters") before calling it; an unbound
QuantumCircuit no longer reaches Aer to fail there (issue #308).
A failure must never cross the seam as a pyo3_runtime.PanicException or a
process abort (it used to: the Rust side unwrap()/panic!-ed on these calls).
The Rust orchestration layer now returns a typed Result on every path:
- A Python exception raised by the seam function itself (the three failure
modes above, or any runtime error inside
run_qcs) is re-raised verbatim, preserving its original type — so theValueError/TypeErrorguarantees above hold unchanged — except an exception raised by Qiskit (issue #218): one whose class, or any class in its MRO, is defined in aqiskit*module (qiskit.exceptions.QiskitError,qiskit_aer.AerError,qiskit.qasm2.QASM2ParseError, …) is raised aspolypus.BackendError, whose message starts with the Qiskit class's qualified name followed by its message, with the original exception chained as__cause__(its traceback is kept). Detection reads class names only, so Qiskit is never imported for it. A Qiskit class that is also aValueError,TypeErrororKeyboardInterruptis still re-raised verbatim: the typed failure modes above, and cancellation, win. The rule lives in one helper,polypus::exceptions::wrap_qiskit_error(qiskit_error_to_pyerron this seam). - The same rule covers the Qiskit calls Polypus makes on the user's Qiskit
circuits outside this seam, before any backend runs:
qml.train/qml.predictcomposingfeature_mapwithansatzand binding each row and the weights, and the VQC/QML oracles binding candidate parameters (assign_parameters_qiskit, which reports a failure of that call asEvaluationError::Qiskit). There a Qiskit exception is raised aspolypus.EvaluationError(qiskit_error_to_evaluation_error) — no backend is involved yet — again withmodule.Class: messageand__cause__, and withValueError/TypeError/KeyboardInterruptkept as they are. An exception raised by the user'sexpectation_function(or variance callback, or theask()/tell()of apolypus.Externaloptimizer, or the trainingcallback, C-5) is never retyped, even when its class is a Qiskit one: it travels inEvaluationError::Pythonand re-raises verbatim. - An external optimizer (
polypus.External, #399). The run calls the user'sask()andtell()from insidedetach, attaching for each call only (attach_or), on the thread that calledtrain. An exception either call raises, a failed conversion of whatask()returned (ValueError), or a Ctrl+C pending before either call, is recorded in the run'sOracleErrorSlotasEvaluationError::Python; the bridge stops, anddispatch_optimizerreturns the recorded error instead of the bridge's, so the edge re-raises the original exception with its class,KeyboardInterruptincluded. Once the slot holds an error (that call's, a backend failure, a Ctrl+C caught between waves), neither method calls Python again, so the library is never told a failed batch's values. With the interpreter unavailable, either call recordsInterpreterUnavailablewithout calling Python. - How the exception travels. Between the seam and the FFI edge it crosses
pyo3-free layers (the planner,
OracleErrorSlot) that may format it while the thread is detached, so it is carried aspolypus_infrastructure::DisplaySafePyErr, never as a barePyErr:seam_errorboxes it intoBackendError::External, a callback observable intoObservableError::External, andEvaluationError::Python/Qiskithold one. ItsDisplay/Debugnever panic, even once the interpreter is unavailable (ENGINEERING.md §9). The edge (external_to_pyerr,observable_error_to_pyerr,evaluation_error_to_pyerr) downcasts only to that carrier and re-raises the originalPyErrit holds, so the class rules above apply to the original exception; a barePyErrin anExternalbox is not recovered and surfaces aspolypus.BackendError(orpolypus.EvaluationErrorfrom an observable) with its message. - The interpreter is unavailable. With the interpreter unavailable (it is
finalizing, say, while a run is still going on a daemon thread), the code a
run reaches inside
detachthat needs Python (the Aer/CUNQA seam calls, the Qiskit binding, the user's callbacks, the between-wave interrupt guard) returns a typed error,polypus_infrastructure::InterpreterUnavailable, that the edge raises asKeyboardInterrupt("the run was aborted: …", the class an interrupted run gets); never a panic. It travels boxed in the sameExternalvariants and is downcast afterDisplaySafePyErr, so a seam exception keeps its class (ENGINEERING.md §9).polypus.statevector, cancelled by its interrupt hook for the same reason, raises the sameKeyboardInterrupt. - A failure originating in the Rust layer (backend construction, a native
circuit that will not parse/simulate, the QMIO network path, a data
conversion, a statevector that does not fit in the memory budget) raises a
class from the
polypusexception hierarchy:PolypusError(base) →BackendError→ {CunqaError,QmioError,NativeCircuitError,InsufficientMemoryError},PolypusError→EvaluationError, andPolypusError→ConfigurationError. Catchingpolypus.PolypusErrorcatches them all. ConfigurationError(issue #418) subclasses bothPolypusErrorandValueError. EveryValueErrorthatrun_quantum_circuit,train,qml.trainandqml.predictraise for an argument or a configuration (an unknowninfrastructure, a badwalltime, an optimizer setting,OracleError::Config, …) is one, so theValueErrorguarantees in this file still hold.trainandqml.trainmake these checks, and convert the observable and the optimizer, before any backend exists, so on CUNQA an invalid configuration never reachesqraise.InsufficientMemoryError(issue #215): a circuit that does not fit in the memory budget —POLYPUS_MEM_BUDGETwhen it is valid (e.g.32G), else the detected RAM/cgroup limit minus a safety reserve — is refused before it runs, on every local path:- the native backend,
polypus.statevector, and the local/Aer backend withsim_method="statevector"refuse in Rust on the16 · 2^n-byte statevector model, before anything is converted or allocated; - the local/Aer backend with any other
sim_method(automatic, the default;density_matrix;matrix_product_state; …) passes the budget to Aer asmax_memory_mb(above), so Aer validates each experiment for the method it actually picks — a large Clifford circuit thatautomaticruns onstabilizerstill fits, while a non-Clifford one, or adensity_matrixrun (16 · 4^n), is refused.python/polypus_python/local.pyraises Aer's refusal (an unsuccessful experiment whosestatuscontains "insufficient memory") aspolypus.InsufficientMemoryError, which crosses back throughseam_error/external_to_pyerrverbatim, keeping its class.
The exact quantum kernel (qml.kernel_matrix(exact=True), C-11 (h)) is
refused the same way when the matrix it keeps beside its statevectors leaves
no room for even one of them (with room for one but not two it computes each
entry from one statevector instead, and the matrix counts on that route too);
its message names the matrix, its bytes and the statevector instead of a
circuit.
The message names the circuit (qubit count, or its index for Aer), the required
and budgeted sizes, where the budget came from, and how to override it with
POLYPUS_MEM_BUDGET. It is never raised against the blind 16 GiB fallback used
when no limit can be detected (macOS, Windows): the Rust check skips it and
max_memory_mb is not sent. A circuit above polypus_sim::MAX_QUBITS (40) keeps its
ValueError (native statevector) / NativeCircuitError (native backend),
checked first. Between 31 and 40 qubits the budget decides on the native
paths (issue #428): a known limit refuses with this error what does not fit
and lets through what does; under the blind fallback such a circuit gets the
ceiling ValueError / NativeCircuitError it got when the ceiling was 30,
its message adding that POLYPUS_MEM_BUDGET lets the budget decide.
A statevector the system refuses to allocate after passing these checks
(polypus_sim::SimError::AllocationFailed: a budget above the real free
memory, or a widening transpiler's circuit) is not this error: it surfaces as
the simulator's other failures do, ValueError from polypus.statevector and
NativeCircuitError from the native backend, with a message naming the
qubits and bytes and "the system refused the memory". With Linux overcommit
the system may instead grant the memory and the process be killed when it is
written; the budget is the guard against that. This replaces the old failure mode, in which such a run was
started and the process killed by the out-of-memory killer with no Python
exception at all.
disconnect_from_infrastructure runs from CunqaBackend's Drop, which must
never panic: a release failure is logged (log::error!) and recorded in the
process-wide polypus.backend_cleanup_failures() counter rather than raised
(see ENGINEERING.md §9). This is independent of the known break below, which is
about which kwarg the Python side reads.
Enforcing test: tests/python/test_seam_contract.py — runs in CI without
SLURM by monkeypatching the polypus_python seam (run_qcs) to force a
failure, asserting it surfaces as a typed Python exception (never a
PanicException) with the C-1 type preserved. For Qiskit exceptions (issue
218): test_seam_qiskit_error_becomes_backend_error (QiskitError,¶
QASM2ParseError, AerError, a user subclass; class name, message and
__cause__), test_seam_non_qiskit_error_is_reraised_verbatim,
test_seam_qiskit_error_that_is_also_a_c1_type_is_preserved, and, without
monkeypatching, test_real_aer_error_reaches_the_caller_as_polypus_error and
test_real_qasm_parse_error_reaches_the_caller_as_polypus_error; plus the
qiskit_* / non_qiskit_python_errors_are_reraised_verbatim unit tests in
crates/polypus/src/exceptions.rs. Outside the seam:
tests/python/test_qml_error_propagation.py (qml.train/qml.predict composing
and binding, both oracles' binding, all real Qiskit failures; the guards
test_qiskit_class_raised_by_a_user_callback_stays_verbatim and
test_qiskit_value_and_type_errors_keep_their_class), the
qiskit_binding_error_maps_to_evaluation_error_with_its_cause,
qiskit_variant_keeps_non_qiskit_and_c1_typed_errors and
python_variant_stays_verbatim_even_for_a_qiskit_class unit tests in
crates/polypus/src/exceptions.rs, and
a_failing_binding_call_is_the_qiskit_variant in
crates/polypus-evaluation/src/lib.rs.
The DisplaySafePyErr carrier: display_safe_py_err_reraises_the_original_exception,
bare_py_err_in_external_is_not_reraised_verbatim and
bare_py_err_in_observable_external_is_not_reraised_verbatim in
crates/polypus/src/exceptions.rs;
display_safe_py_err_formats_like_the_py_err_and_round_trips and
display_safe_py_err_formats_without_an_interpreter in
crates/polypus-infrastructure/src/attach.rs;
python_carrying_errors_format_without_an_interpreter in
crates/polypus-evaluation/src/error.rs; and
a_raising_callback_is_boxed_as_a_display_safe_py_err in
crates/polypus-evaluation/src/py_callback_observable.rs.
An unavailable interpreter: tests/python/test_interpreter_shutdown.py
(test_a_training_run_on_a_daemon_thread_survives_shutdown,
test_a_run_started_while_finalizing_aborts_as_keyboard_interrupt; a real
shutdown); interpreter_unavailable_in_external_maps_to_keyboard_interrupt,
interpreter_unavailable_maps_to_keyboard_interrupt_on_the_evaluation_path and
interpreter_unavailable_maps_to_keyboard_interrupt in
crates/polypus/src/exceptions.rs;
interpreter_unavailable_is_an_error_carried_in_external in
crates/polypus-infrastructure/src/attach.rs; the
seams_fail_typed_without_an_interpreter tests in local.rs and cunqa.rs,
create_backend_without_a_noise_model_does_not_attach in lib.rs and
duplicate_shares_the_object_without_attaching in circuit.rs (same crate);
python_carrying_errors_format_without_an_interpreter and the
*_when_attaching_is_forbidden tests in crates/polypus-evaluation/src/
(create_backend_with_a_noise_model_fails_typed_when_attaching_is_forbidden
among them); signal_polling_cancels_when_the_interpreter_is_unavailable and
statevector_cancellation_raises_keyboard_interrupt in
crates/polypus/src/bindings/interrupt.rs.
An external optimizer: an_exception_is_recorded_with_its_class,
a_failed_run_calls_neither_method and
an_unavailable_interpreter_is_recorded_without_calling_python in
crates/polypus/src/bindings/external.rs,
external_returns_the_failure_recorded_in_the_slot in
crates/polypus-orchestration/src/dispatch.rs,
test_an_exception_from_ask_or_tell_keeps_its_class (a LookupError and a
KeyboardInterrupt from either call) and test_a_failing_cost_is_not_told in
tests/python/test_external.py, and
test_external_training_responds_to_sigint_promptly in
tests/python/test_interrupt.py.
The local run_qcs kwarg set, with max_memory_mb present for a known budget,
is pinned by test_local_run_qcs_kwargs_* in the same file.
InsufficientMemoryError is pinned by tests/python/test_memory_budget.py (the
class hierarchy; subprocess runs with POLYPUS_MEM_BUDGET set on the native
backend, polypus.statevector and Aer — statevector, automatic non-Clifford
and density_matrix refused, a 26-qubit Clifford GHZ on automatic still run;
qml.kernel_matrix(exact=True) with a matrix that leaves no room for a
statevector; local.py consuming max_memory_mb; and the "insufficient memory"
status text of the installed Aer) and by assert_maps_to in
crates/polypus/src/exceptions.rs (the Rust → Python class mapping, for both
refusals).
C-2 · Gate vocabulary symmetry¶
The circuit vocabulary is:
h x y z s t sdg tdg id u0 sx sxdg rx ry rz p u1 u2 u u3 (U → u)
cx (CX → cx) cz cy ch csx swap rzz rxx cp cu1 crx cry crz cu3 cu
ccx cswap rccx rc3x c3x c3sqrtx c4x
calls of gates declared with `gate` blocks
barrier measure measure_all
This is all of Qiskit's qelib1.inc. Gates outside it (ryy, rzx, ecr,
iswap, xx_plus_yy, mcx, …) reach Polypus the way Qiskit's exporter writes
them — declared with gate blocks — and are handled as declared gates. The
OpenQASM 3 profile (C-10) reads and writes the same vocabulary: stdgates.inc
names a subset of it, and the rest is written through gate definitions.
One instruction per statement, re-emitted under the same name. The
importer never decomposes: a ccx statement is one Ccx instruction and is
exported as ccx again, with its operands in the same order, so a benchmark
file reaches a backend (e.g. Aer, through the exporter) as the same program —
same gate count, same depth, same instruction names. The only spelling changes
are the language builtins U → u and CX → cx, which Qiskit names u
and cx itself, so no Qiskit consumer can tell them apart; the OpenQASM 3
profile also reads phase as p and cphase as cp, and writes u as the
builtin U (C-10). An instruction stdgates.inc lacks is written in OpenQASM
3 as a call of a gate the output defines with the same matrix, under the
instruction's name, and reads back as that declared gate (a declared gate is
never recognised as a built-in). Decomposition is allowed at exactly four
lowering boundaries, all confined to their module and invisible to the
OpenQASM exporters: the native simulator, for gates without a dedicated
kernel (ccx, cswap, rccx, rc3x, c3x, c3sqrtx, c4x — through their
exact qelib1.inc definitions, GateInstruction::lowering — and calls of
declared gates); the QIR exporter, for gates without a base-profile
intrinsic; and the Aer path (python/polypus_python/local.py), for what is outside
Aer's basis (ch, rccx, rc3x, c3sqrtx, u0 and calls of declared gates;
c3x and c4x parse as Qiskit's mcx, which Aer runs); and the CUNQA path
(python/polypus_python/cunqa.py), for what CUNQA's circuit converter does not take
(the names outside its SUPPORTED_QISKIT_OPERATIONS: the same gates, plus
mcx). Those two lower the Qiskit circuit just before handing it to the
backend, rewriting only (synthesis and basis translation, as
qiskit.transpile(..., optimization_level=0) does) and only when the circuit
holds such an instruction — a circuit already in the basis is handed over as
it is — and never touch the exported QASM. The Aer path lowers into the
default AerSimulator()'s basis whatever the run's sim_method or
noise_model, which narrow the simulator's target but not what Aer runs. It
may reuse the lowered circuit of an OpenQASM text it lowered before (the parse
is deterministic, so it is the circuit lowering that text afresh gives); the
caller's circuit is never modified.
cu1 and cp are the same operator but distinct instructions: each keeps its
own spelling through import and export (neither is normalised into the other).
Likewise p/u1 (one operator), and u/u3 (one operator) with u2: every
spelling is its own instruction, re-emitted as written.
id is an instruction like any other, never a no-op to drop: it is imported,
exported and round-tripped one-to-one, so the gate count and depth of an
imported circuit match the source program (and what Qiskit computes for it).
Only the QIR lowering drops it (there is no identity intrinsic); the simulator
applies it as the identity. As a unitary it is subject to C-4.
Declared gates. A gate declaration, in OpenQASM 2.0 or in the
OpenQASM 3 profile, is kept as a definition (a template over its formal
arguments, plus its source text) and each call of it is one instruction,
GateInstruction::Custom, a unitary on all its qubits for C-4. A call's angles may be free parameters or expressions
of them (CustomGate::with_arguments); such a call is checked through its whole
body, nested declarations included, whenever its parameters are bound —
binding and the exports that take parameter values report NonFiniteParam or
DivisionByZero there — just as a call with fixed angles is checked when it is
created. The OpenQASM 2.0 exporter re-emits an OpenQASM 2.0 declaration
verbatim (only line endings normalised: every run of carriage returns before a
line feed dropped, so CRLF becomes LF) plus the call — never the expanded body —
so a backend that parses the export builds the same program as from the
original file; every other export prints a definition from its body (C-10).
Canonical OpenQASM 2.0 form: the declarations the circuit reaches (directly or
through other declarations) are emitted right after the include — first those
imported from OpenQASM 2.0, in source order, then those imported from
OpenQASM 3, printed, callees first in order of first use; unreachable
declarations are not re-emitted. Expansion into built-in
instructions is a lowering step of the simulator, the QIR exporter and the Aer
path only.
Redeclaring a gate, or declaring one with a qelib1.inc name (always provided),
is rejected; so is recursion (a body may only call earlier declarations), and
so is naming a gate, parameter or argument pi, sin, cos, tan, exp,
ln or sqrt (keywords of the expression grammar, not identifiers).
Invariant: the consumers/producers of this vocabulary — the OpenQASM 2.0
exporter (qasm.rs) and importer (qasm_import.rs), the OpenQASM 3 exporter
(qasm3.rs) and importer (qasm3_import.rs, whose vocabulary is
stdgates.inc's), the native simulator (polypus-sim) and the QIR exporter
(qir.rs) — must all support the full set, with identical unitary
semantics (the native simulator is the reference; QIR decompositions may
differ only by a global phase; the OpenQASM 3 definitions may not differ at
all, under the profile's Qiskit phase conventions).
Consumers that classify the vocabulary. polypus-qml's exact gradient
(classify in crates/polypus-qml/src/problem.rs) sorts every instruction
kind into the Pauli rotations both its gradients differentiate (rx, ry,
rz, rxx, rzz: the parameter shift and the adjoint), the angle-taking
kinds only the adjoint differentiates (crx, cry, crz, cp, cu1, p,
u1, u/U, u2, cu3, cu, u0), the parameter-free instructions it
copies, and the one angle-taking kind no exact gradient differentiates (the
call of a declared gate), which it rejects. An instruction kind it does not
name is rejected, never passed through, so adding an instruction also means
classifying it there: every_instruction_kind_is_classified fails until it
is, and it lists the three sets of angle-taking kinds explicitly. The native
simulator's adjoint gradient (StatevectorSimulator::adjoint_gradient)
differentiates the Pauli rotations and the adjoint-only kinds above, each
angle through the generator G = i·(∂U)·U† of the matrix it simulates (the
table of generators, family in crates/polypus-sim/src/adjoint.rs; a
gate's angles are numbered in the order GateInstruction::angles lists
them — the one definition of that order in the workspace, which
polypus-qml's untying also follows, and which
c2_angles_follow_the_qasm_argument_order holds to the OpenQASM 2.0
argument order; a call of a declared gate has none), and
steps back through the inverse of every other instruction
(Statevector::push_inverse, which takes GateInstruction::push_inverse's
table below, the one table of the workspace, and itself only keeps the
barriers and measurements, no-ops for the state, and undoes a call of a
declared gate through its expansion: no instruction is added for it);
apply_inverse_undoes_every_instruction_kind
and every_instruction_kind_is_differentiated_through fail until a new
instruction has its inverse, and the latter also until every angle-taking
kind but the declared gate is differentiated;
every_generator_is_the_derivative_of_the_simulated_matrix holds each
generator to the matrix Statevector::apply applies (so a change of phase
convention there fails it).
The inverse of a circuit. ConcreteCircuit::inverse (what the quantum
kernel uncomputes an encoder with, C-11 (h)) is an operation over the whole
vocabulary, with no new instruction: the instructions in reverse order, each
replaced by its exact inverse (global phase included) in the vocabulary — a
self-inverse gate kept, s↔sdg, t↔tdg, sx↔sxdg, every angle negated
(u3(θ, φ, λ)† = u3(−θ, −λ, −φ) under each spelling, cu's γ too), u2(φ,
λ) as u3(−π/2, −λ, −φ); csx, with no inverse among the instructions, as
h, cp(−π/2), h on its target, and rc3x and c3sqrtx, with none either,
as the inverse of their lowering (its instructions in reverse order, each
inverted) — on the same qubits and classical width. Each instruction's inverse
is GateInstruction::push_inverse, public, in its own order of application
inside the reversed circuit. A barrier is kept in its reversed place. A measurement
(measure, measure_all) and a call of a declared gate are refused with
CircuitError::NotInvertible, naming the first; a free parameter or an
expression, which a concrete circuit cannot hold, is the error try_new gives
it. Its match is exhaustive, so a new instruction does not build until it is
inverted; c2_every_instruction_kind_is_inverted_or_refused fails until the
vocabulary list covers it, and polypus-sim's tests/inverse.rs checks every
inverse against the simulator (U then U†, and U† then U, leave a
generic state where it was). The simulator's adjoint steps back through the
same table, so the two cannot drift.
Corollaries:
- Canonical QASM form. The exporter emits a single canonical form (fixed
gate spelling, parameter formatting and declaration order), and the importer
normalises to it. The round-trip guarantee is therefore:
to_qasm2(from_qasm2(to_qasm2(c)))is byte-identical toto_qasm2(c)— i.e. output is a fixed point, without assuming arbitrary hand-written input is preserved byte-for-byte. Semantically,from_qasm2(to_qasm2(c))reproduces the same instruction sequence and parameters asc(except for the two shapes below, which come back in their canonical form), angles bit-for-bit: an angle is written as the shortest decimal that reads back as the same binary64, in the number format of the OpenQASM 3 profile (C-10), so a backend receives exactly the circuit's angles (pi/2is1.5707963267948966; rounded, it is not a Clifford angle to Aer, which then simulates with a statevector instead of the stabilizer method). Conversely, a single gate statement already in canonical form (aqregister, angles in that format, canonical spelling) is re-emitted byte-identically:to_qasm2(from_qasm2(s)) == s. The OpenQASM 3 export has the same fixed-point guarantee,to_qasm3(from_qasm3(to_qasm3(c))) == to_qasm3(c), for its own canonical form (C-10). Both exporters write the canonical form of two shapes the importers normalise: a barrier that lists every qubit in order is written asbarrier q;, and the measurementsq[k] -> c[k]of every qubit in order asmeasure q -> c;(bit by bit when the register is wider thannum_qubits, see Classical width). For these two shapes the read-back reproduces the canonical instructions (Barrier([]),MeasureAll), not necessarily the builder's; any other barrier or measurement, out of order or partial, is kept as built (issue #568). Enforced byc2_full_in_order_barrier_and_measure_runs_are_canonicalincrates/polypus-circuit/tests/contracts.rs. - Classical width. A circuit has one classical register,
c, as wide asclbits_width(): the classical bits the imported program declares (all itscregs, or itsbitregisters in OpenQASM 3, flattened in declaration order), or the implicit register its measurements need (num_clbits():max(cbit) + 1,num_qubitswithmeasure_all) if that is wider or nothing was declared. Binding keeps it, and the OpenQASM 2.0 and 3 exports write it ascreg c[n];/bit[n] c;(C-10) — also for a program that declares a register and measures nothing. Soto_qasm2(from_qasm2(s))declares as many classical bits ass(creg a[2]; creg b[1];becomescreg c[3];), and==compares this width: a declared width no larger than the measurements' is the same as declaring none. A circuit from the builder declares none, so it exports exactly the register its measurements need, and none without measurements. A full measurement into a register wider thannum_qubitsis written bit by bit (measure q[i] -> c[i];), sincemeasure q -> c;needs equal sizes. The QIR export declares it asrequired_num_resultsand records only the measured results, so it may declare results it never records, as a partial measurement already does (one written atc[1]declares 2 and records 1); QMIO'sopenqasm,qirandqir_bitcodeformats thus submit the same width (issue #322). Rationale:docs/adr/0006-declared-classical-registers.md. - Adding a gate is a six-place change plus a row in the equivalence test —
the OpenQASM 2.0 exporter (
qasm.rs), the OpenQASM 2.0 importer (qasm_import.rs), the OpenQASM 3 exporter (qasm3.rs: the gate'sstdgates.incname, or a definition in itsHELPER_PROGRAMwhose matrixcrates/polypus-sim/tests/qasm3_semantics.rschecks), the native simulator (polypus-sim), the QIR exporter (qir.rs) and the Python bindings (crates/polypus/src/bindings/circuit.rs, which expose the builder method, and its stub inpython/polypus/__init__.pyi); the OpenQASM 3 importer (qasm3_import.rs) too, ifstdgates.incnames the gate. This is on top of the IR variant (gate.rs) and its builder method (circuit.rs), after which the compiler flags the text drawer (draw.rs). A PR adding it in fewer places must be rejected. - Non-finite parameters are rejected uniformly. A
NaNor infinite angle is never a valid parameter value: circuit construction and parameter binding reject it (CircuitError::NonFiniteParam), the OpenQASM importers reject it at parse time (CircuitError::Parse), the QASM and QIR exporters refuse to serialise it, and the simulator rejects it (SimError::NonFiniteAmplitude). No producer may emit, and no consumer may accept, a non-finite parameter. - Angle expressions exist only before binding. An angle may be an
expression of the circuit's free parameters (
GateParam::Expr, stored in its circuit byParameterizedCircuit::add_expr; a bare parameter staysParamand a constant expression becomesFixed).assign_parametersevaluates every expression, so the OpenQASM 2.0 and QIR exporters see them only throughto_qasm2_with_params/to_qir_with_params, which evaluate them with the given values, and the simulator only receives bound circuits (an expression left in a hand-assembledConcreteCircuitisSimError::UnboundExpression). Evaluation performs exactly the written operations, in source order, without reassociation. The rule above applies to what an expression takes in and to its final value: a non-finite number in the expression, a non-finite value bound to a parameter it uses, or a non-finite result isNonFiniteParam, and a division by zero isCircuitError::DivisionByZero. An infinite intermediate whose result is finite (1/exp(x)for a largex) is accepted. An expression id means something only in the circuit that issued it; any other circuit rejects it (CircuitError::UnknownExpression).
Enforcing test: parametric round-trip tests over the whole vocabulary in
crates/polypus-circuit/tests/contracts.rs (export → import → export per gate
and for a circuit using every instruction kind — an exhaustive match fails the
build when a new variant is not covered — plus canonical statement → import →
export byte identity per gate, cu1/cp spelling preservation, every
angled gate exported with expressions as with their values, every angled
gate's angles read back bit-for-bit, and the classical width:
c2_declared_classical_width_round_trips and
c2_qasm3_declared_classical_width_round_trips); the classical width of
imported and built circuits through binding, export and == in
test_binding_keeps_the_declared_width_and_the_implicit_register,
test_an_unmeasured_declared_register_counts_for_eq,
test_builder_circuits_compare_as_before and
test_builder_exports_are_unchanged_by_the_classical_width (builder exports
byte-identical to before) in crates/polypus-circuit/tests/circuit.rs, and
builder_qir_is_unchanged_by_the_classical_width in
crates/polypus-circuit/tests/circuit_qir.rs; the
table ↔ exporter spelling check in qasm_import.rs's unit tests; the
QIR-vs-simulator unitary-equivalence test in
crates/polypus-sim/tests/contracts.rs, which parses the QIR actually emitted
for every gate and compares it with the native gate up to global phase; and,
for expressions, crates/polypus-circuit/tests/expressions.rs (binding
semantics, the non-finite and division-by-zero rules, ids foreign to a
circuit, bounds), the calls-with-free-parameters tests in
crates/polypus-circuit/tests/gate_declarations.rs, and
unbound_expression_is_rejected in
crates/polypus-sim/tests/gate_matrices.rs. For OpenQASM 3: the c2_*qasm3*
tests of crates/polypus-circuit/tests/contracts.rs (the whole vocabulary,
gate by gate, stdgates.inc statements byte-identical, the fuzz corpus), and
crates/polypus-sim/tests/qasm3_semantics.rs (every definition the export
writes, against its instruction, as full matrices). For the inverse:
c2_every_instruction_kind_is_inverted_or_refused in
crates/polypus-circuit/tests/contracts.rs, crates/polypus-circuit/tests/inverse.rs
(each kind's inverse, the order, the angles, barriers, the errors, what the
inverse keeps) and crates/polypus-sim/tests/inverse.rs (each inverse against
the simulator).
The Aer lowering boundary is enforced in Python by
tests/python/test_local_aer_lowering.py (every out-of-basis gate and a
declared gate run on Aer with the transpiled reference's counts and the native
backend's distribution; a circuit in the basis is neither copied nor
transpiled), test_run_quantum_circuit_matches_qiskit_on_aer in
tests/python/test_qasm_gate_equivalence.py (the whole vocabulary on the real
execution path) and tests/python/test_backend_compatibility.py. For a Qiskit
QuantumCircuit, polypus.backend_compatibility
(crates/polypus/src/bindings/compatibility.rs) replicates the Aer path's
decision to lower and calls the run's own rewrite to report what the run
would raise; it lowers nothing for execution, so it is not a lowering
boundary, and _assert_coherent in that test, which runs every circuit it
classifies, keeps the two copies in step. The CUNQA
one by tests/python/test_cunqa_lowering.py (every gate CUNQA 3.0.0 does not
convert, and a declared gate, reach run as an equivalent circuit in its list;
a circuit in the list is neither copied nor transpiled).
C-3 · Measurement counts format¶
- Keys are bitstrings of width
num_clbits(ornum_qubitswhen the circuit has no measurements — full-register read-out convention). "No measurements" means nomeasureinstruction (Measure/MeasureAllnatively): classical registers that are declared but never written do not count, and do not change the width. This holds on the Aer and the native backend alike (issue #218; before it Aer raisedQiskitError: No countsfor such a circuit), and on CUNQA, whose vQPUs fail such a job: its seal adds the same read-out (issue #253, checked on CUNQA 3.0.0). - For a circuit with measurements,
num_clbitsis the circuit's classical width (the key width,Circuit.clbits_widthin Python andclbits_width()in Rust — notCircuit.num_clbits/ParameterizedCircuit::num_clbits(), which stay the implicit register sized by the measurements, so that an unmeasured circuit's keys arenum_qubitswide): for an OpenQASM 2.0 program, the classical bits it declares (the sum of all itscregs), even when fewer are written —creg c[3]; measure q[0] -> c[1];gives"010", and the bits no measurement writes read0; for apolypus.Circuitbuilt with the builder, which declares no registers, the implicit widthmax(cbit) + 1(num_qubitswithmeasure_all). Apolypus.Circuitimported withfrom_qasm2/from_qasm3keeps the width its source declares, through parameter binding and through the export Aer receives (itscreg c[n]is the declared width): it is keyed like the source. Aer, the native backend and CUNQA agree on all three (issues #251 and #304; before #251 the native backend usedmax(cbit) + 1for OpenQASM input too; CUNQA was checked on 3.0.0 with 1 and 2 QPUs). The QMIO path is not verified; QMIO receives the declared width in all three program formats (the QIR export'srequired_num_results, issue #322). The QMIO reply parser requires one key width per reply (and per merged register) but does not compare it with the declared width until the QPU's key width is verified (issue #78). - The classical width is bounded. A circuit holds at most
MAX_REGISTER_BITS(1,000,000) classical bits: the importers reject a wider declaration and the builder ameasureinto a bit at or beyond it (ValueErrorin Python, issue #345). The native backend keys outcomes by a 64-bit word, so it refuses a measured circuit wider thanpolypus_sim::MAX_CLBITS(64) bits withNativeCircuitErrorbefore simulating, instead of returning wrong keys, panicking, or spending memory in proportion to the width (issues #345, #346); Aer takes wider registers. - Bit order is Qiskit little-endian: qubit 0 is the least-significant (rightmost) character.
sum(counts.values()) == shotsrequested for that circuit. When shots are distributed acrossnQPUs, the total is conserved: the remaindershots % nis spread over the first QPUs, never dropped.- If several
measureinstructions write the same classical bit, the last measurement wins (OpenQASM 2.0 register semantics). - Every counts dict Polypus hands to Python lists its keys in ascending
bitstring order (
00,01,10,11):RunResult.countsfromrun_quantum_circuitandqml.predict, and the dict aSampleCostcallback receives. A float reduction over.items()therefore adds its terms in the same order in every call and process. Dicts travelling the other way (run_qcs, C-1) may list their keys in any order.
The per-circuit dict format above is unchanged by C-7: run_quantum_circuit
returns that payload inside a RunResult wrapper, whose shape does not
depend on n_qpus (issue #211):
result.countsis always alist[dict]with one dict per QPU replica, in the order the shots were apportioned (lengthn_qpus; length 1 for a single-QPU run). Replicaiholds exactly the shots apportioned to it (shots // n, plus one for each of the firstshots % nreplicas). Whenshots < n_qpus, the replicas apportioned zero shots are empty dicts{}that stay in the list, so its length is stilln_qpus.result.merged_countsis a singledict: the key-by-key sum of every entry ofcounts, i.e. the circuit's total over allshots(forn_qpus = 1it equalscounts[0]). It follows every rule above: ascending key order, andsum(merged_counts.values()) == shots.
qml.predict also returns a RunResult, but there each entry of counts is a
different row's circuit, not a replica of one circuit, so summing them has no
meaning and merged_counts is None. The dict shape, bit order, key order
and shot-conservation rule are exactly as specified here.
Exact probabilities (native backend only).
NativeStatevectorBackend::run_circuits_exact returns, instead of counts, each
circuit's exact basis-state probabilities |amplitude|², keyed exactly as the
counts above (same width and bit order). It draws no samples and no seed: the
values sum to 1 up to rounding, states of probability exactly zero are omitted
as unobserved bitstrings are, and the result is the same bit for bit on every
run. It reads every qubit, so it accepts only a full-register read-out (no
measurement, or measure_all) and refuses a circuit that measures individual
qubits (UnsupportedCircuit). It is not part of the QuantumBackend trait:
"exact" means nothing for a noisy simulator or hardware. Its memory counts
against the budget (#628): the widest statevector is checked before anything
runs (InsufficientMemory), and the result maps of the whole call count
beside the statevectors in flight, each sized from its circuit's non-zero
states before it is built (exact_map_bytes: the hash table and the keys'
buffers) and refused with InsufficientMemoryForResult instead of being
allocated, after the batch has dropped to one circuit at a time; no 2^n
probabilities vector is held beside the statevector. A map handed to
run_circuits_exact_with's reader counts only while it is built and read.
run_circuits_exact_on_states builds no map: its reader gets each
circuit's amplitudes and key width, which polypus_qml::ExactState reads as
the map they would make, bit for bit, so it needs only the statevector
budget; the native QML oracle and the exact expval, jacobian, vjp and
predict read their circuits this way (C-11 (f)). Under the fallback budget
no map is refused. Enforced by the exact_*, a_read_map_*, a_window_*,
a_released_reservation_* and states_* tests in
crates/polypus-infrastructure/src/native.rs,
states_read_as_their_maps_do_bit_for_bit and
states_raise_the_errors_their_maps_raise in
crates/polypus-qml/src/problem.rs,
test_an_exact_run_whose_probabilities_do_not_fit_is_refused_alike in
tests/python/test_memory_budget.py, and the adjoint-versus-shift tests of
tests/python/test_qml_adjoint.py, whose shift runs in a budget of one
statevector.
Enforcing test: shot-conservation assertion in the orchestration tests
(crates/polypus/tests/running_quantum_circuits_local.rs, plus the Python
public-API case in tests/python/test_local_run.py; audit C6); the stable
RunResult shape — counts one dict per replica with its own apportioned
shots (zero-shot replicas kept as {}), merged_counts their key-by-key sum —
in the execute_replicas / merge_counts tests of
crates/polypus-backend/src/planner.rs,
run_circuit_flow_returns_the_per_replica_counts in
crates/polypus-orchestration/src/flow.rs,
distribute_returns_each_replica_with_its_apportioned_shots in
crates/polypus/tests/running_quantum_circuits_local.rs,
TestRunQuantumCircuitMultipleQpus and TestMergedCounts in
tests/python/test_local_run.py, and
test_distributed_counts_shape_is_the_same_on_every_backend in
tests/python/test_backend_selection.py, with merged_counts is None for
qml.predict in tests/python/test_qml_predict.py (issue #211); key order in
tests/python/test_local_run.py (run_quantum_circuit, one and several QPUs,
counts and merged_counts),
tests/python/test_qml_predict.py and tests/python/test_qml_supervised.py
(the SampleCost dict); flat bitstring keys for circuits with several
classical registers (Aer vs native parity) in
tests/python/test_local_run_multi_register.py (issue #206); last-write-wins
in the c3_* tests of crates/polypus-sim/tests/contracts.rs (simulator
semantics, incl. MeasureAll ordering against explicit Measures) and
TestLastMeasurementWins in tests/python/test_backend_selection.py (native
vs. Aer, byte-identical counts; issue #205); the full-register read-out of a
circuit without measurements, whatever cregs it declares, in
TestUnmeasuredCircuitsReadTheFullRegister in
tests/python/test_backend_selection.py (Aer and native, same keys) and
unmeasured_circuit_is_num_qubits_wide_whatever_its_cregs /
format_counts_width_follows_measurement_instructions in
crates/polypus-infrastructure/src/native.rs (issue #218); the declared
classical width of a measured OpenQASM program in
test_measured_circuit_with_a_wider_creg_has_the_same_keys and
TestMeasuredCircuitsUseTheDeclaredClbitWidth in
tests/python/test_backend_selection.py (Aer and native, one and two QPUs,
plus the implicit width of a built polypus.Circuit and the declared width
of one from Circuit.from_qasm2/from_qasm3, the agreement of Aer and native
on such an imported circuit, and the full read-out of an imported circuit
that declares a creg but measures nothing),
format_counts_width_follows_the_declared_clbits,
measured_qasm_is_keyed_at_its_declared_clbit_width,
native_circuit_keeps_the_implicit_clbit_width,
imported_native_circuit_keeps_its_declared_clbit_width and
declared_clbit_width_survives_a_transpiler in
crates/polypus-infrastructure/src/native.rs, and
declared_clbits_is_the_sum_of_the_cregs, builder_circuits_declare_no_clbits,
the_export_keeps_the_declared_width,
the_width_is_never_narrower_than_the_measurements,
a_measurement_within_the_declared_width_keeps_it,
declared_width_is_part_of_eq_and_kept_by_clone and
a_zero_size_creg_is_rejected in
crates/polypus-circuit/tests/qasm_import.rs and
declared_clbits_is_the_sum_of_the_bit_registers and
declared_clbits_is_exported in
crates/polypus-circuit/tests/qasm3.rs (issues #251 and #279);
qir_declares_the_imported_classical_width in
crates/polypus-circuit/tests/circuit_qir.rs and
qir_formats_declare_the_classical_width_of_the_openqasm_program in
crates/polypus-infrastructure/src/qmio.rs (issue #322);
test_clbits_width_is_the_declared_width in
tests/python/test_qasm_import.py (issue #323), plus the
circuit-side tests listed under C-2; on CUNQA, the full read-out, the flat key
of several registers and the declared width in
test_circuit_without_measurements_reads_the_full_register,
test_several_registers_give_one_key_without_spaces and
test_declared_classical_width_is_kept in
tests/python/test_cunqa_run_flow.py (against a fake that answers as CUNQA
3.0.0 did) and tests/python/test_cunqa_real.py (a real family, opt-in;
issues #253 and #304).
C-4 · Measurement placement (terminal measurements)¶
Polypus circuits are straight-line programs with terminal measurement: no gate may act on a qubit after that qubit has been measured, and each classical bit is written at most once (exception: the C-3 last-write-wins rule exists only to define behaviour for hand-assembled circuits).
Backends and exporters must reject circuits that violate this with an explicit error — never silently reorder, deduplicate or no-op the measurement. The rule is enforced at four points, which must all reject identically (same offending qubit, same error) even though they see the circuit differently:
- Builder (
ParameterizedCircuit::try_push/pushandtry_compose/compose): incremental, push-time. Each push is checked against the per-circuit record of qubits already measured, which the push itself then updates — the prefix is known to be valid, so only the new instruction can offend. Rescanning here would make building a circuit quadratic in its gate count (issue #109).try_compose/composecheck every instruction of the composed circuit against that same record, in order, before appending any, so a rejected composition leaves the circuit unchanged. - QASM importer: incremental, parse-time, against the parser's own
measuredset (which also carries the offending line number). - Simulator (
polypus-sim) and QIR exporter: a single full-sequence scan viapolypus_circuit::terminal_measurement_violation, since both are handed a complete instruction list — possibly hand-assembled, i.e. never validated by the builder or the importer.
terminal_measurement_violation is the reference definition of the rule: a
unitary on a measured qubit is a violation, Barrier is always allowed, and
re-measuring an already-measured qubit is allowed.
Rationale and alternatives considered: see docs/adr/0001-terminal-measurements.md.
Enforcing test: rejection tests in
crates/polypus-circuit/tests/contracts.rs (builder, importer, QIR exporter)
and crates/polypus-sim/tests/contracts.rs (simulator).
C-5 · Optimizer ↔ oracle contract (polypus-optimizers)¶
EvaluationOracle::evaluate_batch(candidates)returns exactlycandidates.len()finitef64values, in order; higher is better. Python-backed oracles must validate length before returning across the FFI.- Preconditions validated with an error (not a panic): DE
population_size >= 4(with everystrategy); PSO/QNGbounds.0 < bounds.1;dimensions >= 1;initial_pointas below. - Starting point (
initial_point). Every optimizer takes an optional starting point: theinitial_point: Option<Vec<f64>>field ofAlgorithmDifferentialEvolutionArgs,AlgorithmPSOArgs,AlgorithmQNGArgs,AlgorithmCmaEsArgs,AlgorithmAdamArgs,AlgorithmSPSAArgsandAlgorithmRotosolveArgs, the last argument ofdispatch_optimizer, andtrain(..., initial_point=None),qml.train(..., initial_point=None)andqml.Model.fit(..., initial_point=None)(keyword-only;dimensionsis the model'snum_params, C-11) in Python. - Preconditions: exactly
dimensionsvalues, every one finite, and for PSO every value within[bounds.0, bounds.1](PSO clamps positions to its bounds, so a point outside them would be moved). QNG and Adam take any finite point: theirboundsonly shape the random draw. SPSA and Rotosolve, which have nobounds, take any finite point too. Each optimizer checks this after its other preconditions, whose errors come first, and before any RNG draw or oracle call, asOptimizerError::InvalidConfigforinitial_point. Each optimizer'scheck_preconditionsmakes these checks, configuration and point, in that order, without running anything;Method::check_preconditionsinpolypus-orchestrationcalls the one the method names, andtrain,qml.trainandqml.Model.fitcall it before anything runs, with or without a point (no backend, no CUNQA allocation), raisingpolypus.ConfigurationError(aValueError) with the optimizer's message, so a configuration error comes first there too. - Postconditions: the optimizer draws everything exactly as without a
point, then the point replaces part of it, so the RNG stream is
unchanged. DE (every strategy): the point, wrapped into
[0, 2π), is the first member of the initial population, so it is the first candidate of the first batch and every other member is the one drawn without it. PSO: it is the first particle's position (its velocity is the drawn one), so likewise the first candidate of the first batch. QNG: it is θ₀, so the first batch is the finite-difference stencilθ₀ ± h·eᵢaround it. Adam: it is θ₀, the first candidate it measures, where the first gradient is taken: with aFiniteDifferenceGradientthe first batch is θ₀ followed by that stencil, and with an exact gradient θ₀ is the first single-candidate batch. CMA-ES: the point, wrapped into[0, 2π)like every candidate, is the mean of the first run, IPOP restarts draw a fresh mean as without it, andsigma0is not changed. SPSA: it is θ₀, unwrapped, the centre of the calibration batch and the first candidate of the first iteration's batch, its first measurement. Rotosolve: it is θ₀, unwrapped, the first candidate of the first batch, followed by its two neighbours along the first parameter; each coordinate is wrapped into[0, 2π)only when a step updates it. Every other postcondition of this contract holds with a point. Without one (None, the default) every optimizer is bit for bit what it was beforeinitial_pointexisted. Externaltakes no point: the external library chooses its start, soAlgorithmExternalArgshas noinitial_pointfield, andAlgorithmExternal::check_preconditionschecks the configuration only.dispatch_optimizerandMethod::check_preconditionsreturnInvalidConfigforinitial_pointwithMethod::External, after its configuration errors and before anyask, andtrain,qml.trainandqml.Model.fitraiseValueErrorbefore anything runs, in place of the length and finiteness checks, pointing to theinitial_pointof thepolypus.ask_telladapters (and pycma'sx0).- Enforced by
crates/polypus-optimizers/tests/initial_point.rs(the first batch of PSO and every DE strategy against the same seed without a point, QNG's stencil around the point, Adam's first batch of the point and its stencil, Adam's run from the θ₀ its seed draws against the run without a point, CMA-ES's first generation, a far point that still moves, and its restarts against the same seed without a point, SPSA's calibration centred on the point and the point measured first, SPSA's run from the θ₀ its seed draws against the run without a point, Rotosolve's first batch and its run from the θ₀ its seed draws against the run without a point, the rejections before any oracle call and their precedence, PSO's bounds, the postconditions over 10 seeds, and PSO's and QNG's outcome without a point pinned to the bits they had before it), thecheck_initial_pointunit tests insrc/util.rs,initial_point_reaches_every_optimizerandcheck_preconditions_agrees_with_dispatchincrates/polypus-orchestration/src/dispatch.rs, andtests/python/test_initial_point.py(theValueErrors, PSO's bounds included, before the CUNQA seam is reached, a configuration error before the point's, the first candidates every optimizer sends throughtrainandqml.train, and abest_paramslist, tuple or NumPy array as the point), andtests/python/test_qml_native_initial_point_final_shots.py(the same rejections and their precedence throughqml.Model.fit, before the CUNQA seam, the first candidates every optimizer sends for a native model, a list, tuple or NumPy array as the point, and a model saved and read back withqml.loadtrained on from itsparams). The pinned"rand1bin"outcome andtests/python/test_determinism_baseline.pyare unchanged. - Postcondition of every optimizer:
best_fitnessis the oracle's value for the returnedbest_params(audit C4). - Final re-evaluation (
final_shots).train(..., final_shots=None),qml.train(..., final_shots=None)andqml.Model.fit(..., final_shots=None)(both keyword-only) and thefinal_shots: Option<u32>field ofTrainFlow(polypus-orchestration) re-evaluate the optimizer's best candidates once it has stopped, in one more batch withfinal_shotsshots per circuit. EvaluationOracle::evaluate_batch_with_shots(candidates, shots)hasevaluate_batch's contract (exactlycandidates.len()finite values, in order) with every circuit measured withshotsshots. Its default callsevaluate_batch, which is exact for an oracle without shots;VqcOracle,QmlOracleandPauliSumOracleputshotsin everyCircuitTaskof the batch, every training circuit of each candidate for QML and every measurement group's circuit of each candidate for a Pauli sum, and the Planner reads them from the tasks.Arc<T>and the walltime watch forward it. No optimizer calls it.- Seed: the batch is the run's last call to the backend (or last calls,
one per window, for an oracle that windows its candidates:
QmlOracleandPauliSumOracle), which gives it sampling streams of its own (C-7), so its shot noise is independent of the training's even for a candidate re-evaluated at the position it was scored at, asbest_paramsat index 0 is for QNG, Adam and SPSA, and a seeded run still reproduces it. - Preconditions: an integer from 1 to 4294967295.
train,qml.trainandqml.Model.fitraiseValueErrorfor an integer out of that range (0, a negative, 2³²) andTypeErrorfor anything that is not an integer (afloat, abool, astr), as forshots, before anything runs (no backend, no CUNQA allocation), next to theinitial_pointcheck; a NumPy integer is accepted.qml.Model.fitalso refuses any valid value withexact=True, which uses no shots, after this check (C-11). In Rust,Some(0)isOptimizerError::InvalidConfigforfinal_shotsbefore the oracle is built. - Which candidates: during the run the optimizer scores through a
decorator that keeps the best distinct candidates it saw. Only finite
values enter; candidates are distinct by their exact bits, a candidate
scored again keeps its best value, and equal values rank by the order
the candidates were scored (batch by batch, in batch order), so the
choice is deterministic. The batch is
best_paramsfirst, then the best others, up toMethod::final_candidates(): 5 for DE (every strategy), PSO, CMA-ES and External (the bridge cannot tell whether the library searches globally or locally), 1 (best_paramsalone) for QNG, Adam, SPSA and Rotosolve; fewer when the run scored fewer distinct finite candidates. - Postconditions: the batch is sent only after the optimizer returned a
result, whatever stopped it (its budget, convergence, a
callbackthat returnedTrue); an optimizer error, an interrupt or an exception from thecallbackskips it, and a failure or an interrupt in the batch is raised as in any batch, with no result.TrainResult.final_paramsis the candidate with the highest re-evaluated value (the earlier on a tie, sobest_params; aNaNnever wins over a number) andfinal_fitnessthat value; if every value isNaN, which only a custom Rust oracle can return, they arebest_paramsandNaN, with a warning. Both areNonewithoutfinal_shots.final_fitnessis a fresh estimate of the value offinal_paramswithfinal_shotsshots: without bias when the batch holdsbest_paramsalone, and slightly optimistic when it holds several, being the highest of them, though far less thanbest_fitness, the highest of the whole run.best_params,best_fitness(still the value the optimizer measured forbest_params),fitness_history,iterations_runandconvergedare the optimizer's, unchanged; before the batch, the run logs them (best_paramsandbest_fitnessat full precision) atINFO, and again as aWARNINGif the batch fails, since the run then returns no result; in Rust,TrainOutcome::optimizationis theOptimizationOutcomeandFinalEvaluationholds the batch (candidates,values,shots) and its choice. The batch comes after every circuit the optimizer sent, so with the same seed everything before it is bit for bit the run withoutfinal_shots(C-7). It is not counted initerations_runorfitness_history, and not in the CUNQA walltime projection. - Enforced by the unit tests in
crates/polypus-orchestration/src/final_batch.rs(the five best distinct finite candidates,NaNand infinities, repeats,-0.0, ties,best_paramsfirst,Method::final_candidatesfor every variant, the winner, aNaNand an all-NaNbatch, a wrong length),final_shots_add_one_batch_after_an_unchanged_runinsrc/flow.rs(every optimizer, with and without a walltime watch, over an oracle whose noise depends on the candidates scored before, as the native backend's does: the same batches and outcome, then one batch with the shots and the expected candidates) with the error, interrupt, optimizer error, failing final batch, its warning andSome(0)tests there,a_batch_with_shots_is_forwarded_untimedinsrc/walltime.rs, thea_batch_with_shots_puts_them_in_every_tasktests ofVqcOracle,QmlOracleandPauliSumOracle(the shots and the run's seed in every wave),a_final_shots_batch_does_not_repeat_the_training_noiseandde_trains_h2_to_within_three_sigma_of_fciincrates/polypus-evaluation/tests/pauli_sum_h2.rs(new noise for the same candidate, and a final batch throughTrainFlowthat does not repeatbest_fitness), the trait's tests incrates/polypus-optimizers/src/objective.rs, andtests/python/test_final_shots.py(theValueErrors andTypeErrors before the CUNQA seam, the final batch of every optimizer through both entry points at the seam: its shots, its seed, its candidates, the winner and the unchanged batches before it; an error, an interrupt and a failing final batch; a real Aer run whose final batch is measured afresh; and seeded native runs unchanged with a final value measured withfinal_shots), andtests/python/test_qml_native_initial_point_final_shots.py(the same throughqml.Model.fit: the rejections before the CUNQA seam, the refusal withexact=Trueand its order, the final batch at the Aer seam with its shots and every sample, minibatches included, seeded native runs of every optimizer unchanged by it, and a final value measured afresh withfinal_shotsthat estimates the exact value offinal_paramswithin its statistical error). - Watching and stopping a run (
callback, #500).train(..., callback=None),qml.train(..., callback=None)andModel.fit(..., callback=None)(keyword-only in all three) call the user's callback once per iteration of the optimizer, which can watch the run, stop it on a criterion of its own, or write a checkpoint. In Rust:Optimizer::optimize_observed(args, observer)(withoptimizeits default, an observer that never stops) andAlgorithmDifferentialEvolution::optimize_with_strategy_observedshow anIterationObserveranIterationReport(iteration,best_fitness,best_params);TrainFlow::observer(polypus-orchestration) holds aTrainObserver, shown aTrainProgressthat addsevaluations, throughdispatch_optimizer_observed; the edge'sPyTrainObservercalls the Python callback with apolypus.TrainProgress. - Preconditions:
Noneor a callable; anything else raisesTypeErrorbefore anything runs (no backend, no CUNQA allocation), right after thefinal_shotscheck intrain,qml.trainandModel.fit. - What an iteration is: a generation of DE (every strategy), PSO and CMA-ES
(counted across IPOP restarts), an iteration of QNG, Adam and SPSA, a step
of Rotosolve (one parameter), and an ask/tell batch of External, reported
once it has been told. The callback is called exactly
iterations_runtimes, withiteration1, 2, …, at the end of each iteration, after everything the iteration measures; a stop it asks for wins over the optimizer's own stopping test (and a CMA-ES restart) on that iteration. It is not called after the optimizer returns: not for thefinal_shotsbatch, nor for the re-score of a minibatched run'sbest_fitness. - What it sees (
polypus.TrainProgress, a frozen class):iteration;best_fitness, the entry the iteration leaves infitness_history(so the last call seesfitness_history[-1]and, for a run that ends there,best_fitness), non-decreasing;best_params, the parameters it belongs to, a newliston every access, so mutating it never reaches the run; andevaluations, the candidates scored as a fitness so far: every candidate the optimizer hands toevaluate_batch(on the minibatch and, for a minibatched Adam, on every sample), plus each θ an exact gradient scores in its own batch (GradientOracle::value_and_gradient). The gradient's shifted circuits, QNG'svariance_functionand thefinal_shotsbatch are not counted. A candidate is one circuit intrainand one per training sample inqml.trainandModel.fit. With a minibatch,best_fitnessis the minibatch estimate the search uses, except for Adam, which tracks its best on every sample (see "Minibatches" below). - Adam, SPSA and Rotosolve measure the point their last step reached once the run ends: that measurement is made within the last iteration, before its call, so the last call already sees the run's final best.
- Return value:
True, or a NumPybool_that is true, stops the run after that iteration;NoneandFalse(and a falsebool_) let it go on. Any other value (anint, afloat, alist, a NumPy number) is aTypeErrornaming it, raised as the run's error with no result, on that same iteration. - Postconditions of a stop: the run returns a
TrainResultwithiterations_runthe iteration that stopped it,len(fitness_history) == iterations_run,converged = Falseandstop_reason = "callback"(also when the optimizer's own test fired on the same iteration: the stop wins),best_paramsandbest_fitnessthose of the last call (with a minibatch, except for Adam,best_fitnessis then re-scored on every sample, as after any run; see "Minibatches" below), and every other postcondition of this contract (best_fitnessis the oracle's value forbest_params,fitness_history[-1] == best_fitness). Nothing is evaluated after it: no oracle call, and for External no furtherask(). Adam, SPSA and Rotosolve leave the point a stopped iteration's step reached unmeasured (the last iteration measures it before its call, as above). Withfinal_shots, the final batch is still sent. A stop on the first iteration is valid. - An exception the callback raises propagates unchanged, class and message,
KeyboardInterruptincluded: it is recorded in the run'sOracleErrorSlotasEvaluationError::Python, the run stops at once (no further call, no oracle call, nofinal_shotsbatch) and returns no result (C-1 "Failure modes"). Once the slot holds any failure (an oracle, a backend, a Ctrl+C caught between waves), the run stops at the end of that iteration without calling the callback. With the interpreter unavailable, the call recordsInterpreterUnavailable, raised asKeyboardInterrupt, without calling Python. - Ctrl+C: the call checks for a pending signal before the user's code runs,
as the External bridge does, so a SIGINT during a run with a callback
raises
KeyboardInterruptas promptly as without one. - Without a callback, or with one that never stops the run, a seeded run is bit for bit the same as before (C-7): the observer only reads, and the evaluation counter forwards every call unchanged.
- Enforced by
crates/polypus-optimizers/tests/observer.rs(every optimizer, DE in its three strategies and CMA-ES with and without restarts, over 4 seeds: an observer that never stops leaves the outcome and every batch unchanged; one report per iteration with its history entry, the last one included; a stop at the first, second and next-to-last iteration with the postconditions recomputed from the fitness function and no oracle call after it; a stop on the iteration where the optimizer's own test fires; noaskafter a stop), theWatching a runtests incrates/polypus-orchestration/src/dispatch.rs(the evaluation count for DE, Adam with a finite difference, an exact gradient with and without its own θ, and a minibatched Adam; a failed slot stops the run without showing it; an error the observer records is the run's) and insrc/flow.rs(every optimizer: the count against the candidates scored and without the final batch; a stop that still sends the final batch; an observer error that skips it; a failed run never shown), thecallbacktests incrates/polypus/src/bindings/callback.rs(the record, read-only and copied;True,np.bool_,None,False; theTypeErrorfor any other value; an exception recorded as itself; a failed run not calling Python; theTypeErrorfor a non-callable) anda_callback_is_checked_after_final_shots_and_before_the_backendinbindings/entry_tests.rs,tests/python/test_callback.py(theTypeErrorbefore the CUNQA seam in all three entry points and afterfinal_shots; keyword-only; one call per iteration for every optimizer throughtrain,qml.trainandModel.fit, withevaluationsequal to the circuits sent, and no call for a minibatched run's re-score; a stop withTrueandnp.bool_(True)and its postconditions, with nothing sent after it and the final batch still sent; an exception and aKeyboardInterruptraised as themselves with no final batch; theTypeErrorfor other return values; a callback that never stops leaves a seeded result unchanged, also replayed in a fresh interpreter), and the SIGINT-with-a-callback tests intests/python/test_interrupt.py(trainandModel.fit).tests/python/test_determinism_baseline.pyand the pinned"rand1bin"outcome are unchanged. - DE early stopping — fitness stagnation. DE stops early on best-fitness
stagnation, not on population-spread collapse. With
fitness_history[g]the best fitness at the end of generationg(0-indexed; DE maximises, so this series is monotonically non-decreasing), the run stops at the first generationgsuch that
g >= patience and fitness_history[g] - fitness_history[g - patience] < tolerance
i.e. the best fitness improved by less than tolerance over the last
patience generations. Consequences:
- tolerance is a minimum cumulative fitness improvement in the oracle's
own fitness units — not a population standard deviation in parameter
units. (This replaces the former "max per-dimension population std <
tolerance" collapse test, which on QAOA-like landscapes fired within ~5
generations, long before the fitness had plateaued.)
- patience (generations; DE binding default 20) is the look-back window.
No early stop can fire before generation patience, so a larger value makes
the optimizer more patient. Exposed as polypus.DE(..., patience=20). It
must be at least 1: 0 would compare a generation's best fitness with
itself and stop the run at once, so it is an OptimizerError::InvalidConfig
before any RNG draw, for every strategy and for CMA-ES too (in Python, the
ValueError of train/qml.train before any QPU is requested).
- The search dynamics of the default strategy="rand1bin" are DE/rand/1/bin
with angles initialised in [0, 2π) and a fixed mutation factor F and
crossover rate CR: polypus.DE(mutation_factor=None,
crossover_rate=None), None meaning 0.8 and 0.7 (Rust:
AlgorithmDifferentialEvolutionArgs::{mutation_factor, crossover_rate},
AlgorithmDifferentialEvolution::DEFAULT_*). F must be finite and in
(0, 2], CR finite and in [0, 1]; a value out of range, or any value
with "shade" or "lshade", which adapt both, raises ValueError when
the DE object is created or the attribute set (Rust:
OptimizerError::InvalidConfig from check_preconditions before any RNG
draw). One coordinate of each trial, j_rand, always comes from the
mutant, so no trial is a plain copy of its parent (#410). The "shade"
and "lshade" strategies below stop by the same rule. PSO still uses the per-dimension std-collapse test;
QNG has no early stop.
- DE strategies. polypus.DE(strategy=...) (Rust: DeStrategy and
AlgorithmDifferentialEvolution::optimize_with_strategy) picks how trial
vectors are built. Any name other than "rand1bin", "shade" and
"lshade" raises ValueError when the DE object is created or the
attribute set, so no run starts with one (in Rust, DeStrategy::from_str
returns OptimizerError::InvalidConfig).
- "rand1bin" (the default, and what Optimizer::optimize always runs) is
the DE/rand/1/bin above. Its seeded output is pinned bit for bit, so the
other strategies cannot change it.
- "shade" is SHADE (Tanabe and Fukunaga, CEC 2013): current-to-pbest/1
mutation with an archive of replaced parents, binomial crossover, and F
and CR drawn per individual from a memory of the values that improved
their parent. As in the paper, a trial replaces its parent when it is at
least as fit; "rand1bin" needs it strictly fitter.
- "lshade" is L-SHADE (CEC 2014): SHADE with its memory rules, plus a
population that shrinks after every generation, linearly in the
evaluations spent, from population_size to 4 when the evaluation budget
population_size × (generations + 1) runs out. The best members survive
and the archive shrinks with the population. For L-SHADE, generations
sets that budget, which is also "rand1bin"'s maximum, not the number of
generations: the run goes on in more, smaller batches until the next
generation would overshoot the budget, so it never exceeds the budget and
stops less than one final population short of it (with the defaults, 275
generations and 5048 of 5050 evaluations). The schedule depends only on
population_size and generations: DeStrategy::max_generations counts
it by stepping the schedule the optimizer follows, and the walltime
projection (run_shape) uses that count.
- The adaptive strategies share with "rand1bin" the initial population
(the same draws from the same seed), difference vectors taken as the
shortest arc in (−π, π], so an optimum on the 0/2π seam is found as well
as one at π (#410), mutated angles wrapped into [0, 2π) (the parameters
are periodic), one oracle batch per
generation after the initial one, its length checked, the evaluation
budget, the stagnation stop above (patience counts generations for
L-SHADE too) and every postcondition of this contract. "rand1bin" and
"shade" run at most generations generations, "lshade" at most
DeStrategy::max_generations.
- Quality trajectory. Every optimizer reports fitness_history: Vec<f64> —
the best fitness at the end of each executed generation/iteration, so
fitness_history.len() == iterations_run and fitness_history.last()
equals best_fitness (the one exception, a minibatched run of a population
method or QNG, is under Minibatches below). It is surfaced on the Python
TrainResult.
- CMA-ES (AlgorithmCmaEs, exposed as polypus.CMAES: Hansen's
(μ/μ_w, λ)-CMA-ES with IPOP restarts).
- Preconditions, each an OptimizerError::InvalidConfig before any RNG
draw or oracle call: dimensions >= 1 (unlike DE and PSO, which accept
zero), generations >= 1 (there is no initial batch), sigma0 finite and
in (0, 2π], population_size >= 2 when given (None is Hansen's
4 + ⌊3 ln d⌋), population_size · 2^restarts within u32, and
patience >= 1, as DE's.
- One evaluate_batch call of λ candidates per generation, its length
checked, and no separate initial batch. The mean and samples stay
unwrapped in ℝ^d; each candidate is wrapped into [0, 2π) when handed to
the oracle. Only the ranking of the fitness values (NaN last) reaches
the search, so a strictly increasing transformation of the fitness
samples the same candidates. The largest coordinate standard deviation
σ·max√C_ii is capped at max(σ₀, π/2): a wider normal wraps to an
almost uniform distribution on the circle, where the step size would
drift without bound.
- A run ends on fitness stagnation (the rule above, applied to that run's
own best fitness) or on a degenerate distribution: a non-finite state, a
covariance condition number above 1e14, or a largest coordinate
standard deviation σ·max√C_ii below 1e-12·σ₀ or above 1e4·σ₀.
While restarts remain, the next run starts from a new uniform mean with
twice the population (IPOP); otherwise the optimisation stops with
converged = true. Without restarts this is DE's stop exactly. The
generations budget is shared by all runs.
- best_params/best_fitness are the best candidate the oracle scored over
all runs (never the unevaluated mean), and fitness_history is the best
so far after each generation, across restarts.
- CmaEsBatchSchedule bounds every batch's size before the run starts
(exact without restarts), for callers that budget the run. The CUNQA
walltime warning uses it: one batch per generation, and with restarts the
worst case of a restart after every generation
(crates/polypus-orchestration/src/walltime.rs).
- Enforced by crates/polypus-optimizers/tests/cmaes.rs
(best_params_fitness_invariant_holds_across_seeds checks every
postcondition above against the batches the oracle saw, over 25 seeds with
and without restarts; the stagnation, restart, batch-size, wrapping,
invariance, non-finite, short-oracle and configuration tests) and the unit
tests in crates/polypus-optimizers/src/cmaes.rs and src/linalg.rs;
through Python by tests/python/test_cmaes.py (configuration rejected
before any batch, batch sizes and restarts at the seam) and the CMA-ES
cases of tests/python/test_oracle_contract.py.
- Adam (AlgorithmAdam, exposed as polypus.Adam, ascending the
fitness by one of two AdamRules: Kingma and Ba's Adam with bias
correction, the default, or Polyak's heavy-ball momentum) and its
GradientOracle.
- GradientOracle::gradient_batch(theta, dims) returns exactly dims
finite values, ∂fitness/∂θ in parameter order, uphill (the same sign
convention as EvaluationOracle). A wrong length is
OptimizerError::OracleLengthMismatch, and a non-finite component
OptimizerError::NonFiniteGradient (its index and value), before θ
moves.
- GradientOracle::value_and_gradient(theta, dims) returns θ's fitness
and the gradient from one call, or None (the default) when the oracle
does not score θ itself. The value must be the one Adam's own
EvaluationOracle returns for θ, since Adam reports it as measured: an
implementation computes it with that oracle, shared through an Arc.
- Preconditions, each an error before any RNG draw or oracle call:
max_iters >= 1, dimensions >= 1, learning_rate finite and > 0,
beta1 and beta2 in [0, 1), epsilon finite and > 0,
patience >= 1 (InvalidConfig, with either rule, although momentum
uses neither beta2 nor epsilon; a patience of 0 would compare an
iteration with itself), bounds finite with lb < ub (InvalidBounds),
and initial_point as under Starting point above. AdamRule parses
only "adam" and "momentum" (InvalidConfig for rule otherwise);
polypus.Adam(rule=...) raises ValueError for any other name when it
is passed or set.
- The initial θ is initial_point when given, otherwise drawn uniformly
from bounds, and is not wrapped afterwards. Each iteration measures the
current θ and the gradient there, then steps, so max_iters counts
steps. When the gradient oracle scores θ (value_and_gradient), that
is one call: with a
FiniteDifferenceGradient, one evaluate_batch of 2·dims + 1
candidates, [θ, θ+h·e₀, θ−h·e₀, …]. Otherwise Adam scores θ in one
evaluate_batch of one candidate, its length checked, and then calls
gradient_batch. The gradient's length and finiteness are checked either
way, before the step. After the last step, the max_iters-th or the one
after which the run stagnated, Adam scores the θ it reached in one
evaluate_batch of one candidate, its length checked, so every gradient
feeds a measured step.
- best_params is the measured θ with the best fitness and best_fitness
the value the oracle returned for it; the stencil's θ ± h·e_i only give
the gradient and never compete. fitness_history[t] is the best
measured up to iteration t, the final θ counted in the last entry.
The first measurement is kept and later ones only when strictly better,
so a NaN never wins over a number (a run
that only measures NaN reports its first θ and that NaN, unless its
gradient is NaN too, as a finite difference of those values is, which is
NonFiniteGradient).
- AdamRule::Adam steps θ += learning_rate·m̂/(√v̂ + epsilon), with the
bias corrections 1 − β₁ᵗ and 1 − β₂ᵗ carried as running products.
AdamRule::Momentum steps v ← beta1·v + learning_rate·g, θ += v, so
its step, unlike Adam's, scales with the cost. Both use only +, −, ×, ÷
and sqrt, so a seeded run over a backend whose results do not depend on
the platform reproduces bit for bit on every platform (C-7).
- A run ends on fitness stagnation, the rule above with patience counted in
iterations, and then reports converged = true. The rule is checked
after each step, on the θs measured up to it; the θ that step
reached is then measured as above, and can raise the last entry.
- FiniteDifferenceGradient turns any EvaluationOracle into a
GradientOracle by central differences with a step h (finite and > 0):
one evaluate_batch of 2·dims candidates,
[θ+h·e₀, θ−h·e₀, θ+h·e₁, …], per gradient, and θ in front of them for
value_and_gradient. It approximates; an exact gradient is its own
GradientOracle. If the wrapped oracle returns the wrong number of
values, or a parameter index is out of range for θ, the gradient is
empty, without a panic, so Adam reports the length mismatch. An Arc of
an oracle is an oracle, so one scorer can feed both, and must when the
adapter returns θ's value.
- Enforced by crates/polypus-optimizers/tests/adam.rs (one batch of θ
and its stencil per iteration, then the final θ alone, after a single
iteration and after the stagnation stop too; the C-5 postconditions
against the batches the oracle saw over 25 seeds, with each rule and with
an exact gradient, which is scored as one single-candidate batch per
iteration and one for the final θ; convergence on a sphere and a
periodic cosine with each rule; a NaN fitness, never
the best, and an oracle of only NaN; the initial point as the first θ;
stagnation; a seeded run of each rule pinned bit for bit; Adam's update
against a reference of Kingma and Ba's Algorithm 1; momentum's
recurrence, its scale dependence and its unused beta2 and epsilon;
the rule names; every rejected configuration, patience = 0 included,
with no oracle call; the gradient length and finiteness checks; and the
finite-difference stencil,
θ first in value_and_gradient, its accuracy, its step validation, a
broken wrapped oracle and an index out of range) and the BestMeasured
unit tests in src/util.rs.
- In a training run the gradient comes from the run's Oracles
(polypus-orchestration): the exact one when the factory provides it,
otherwise a FiniteDifferenceGradient of the evaluation oracle with
AdamConfig::finite_difference_step. QmlOracleFactory provides the
exact parameter-shift gradient for a native QML model, which also scores
θ through value_and_gradient when there is no minibatch, so such an
iteration is one call (C-11 (f)); neither it, for Qiskit circuits, nor
VqcOracleFactory provides a gradient otherwise, so those runs take the
finite difference, built over the run's evaluation oracle so that θ's
value is that oracle's. A GradientOracle declares in advance, through
scores_theta (default false), whether its value_and_gradient scores
θ in the gradient's own batch: true exactly when it returns a value,
as FiniteDifferenceGradient always does and QmlOracle does without a
minibatch. The CUNQA walltime projection (Method::run_shape_over)
counts one batch per iteration when the gradient scores θ (the finite
difference the run builds with no gradient and no minibatch, or a given
gradient whose scores_theta is true), and two (θ, then the
gradient) with a given gradient that does not, or with a minibatch and no
given gradient; the final θ counts as one more iteration, exact with
one batch per iteration and a bound on its single candidate with two. The
watch forwards every call, value_and_gradient and scores_theta
included, value_and_gradient counted as a batch only when it returns a
value, so Adam sends the same batches with and without it. Enforced by
scores_theta_tells_whether_value_and_gradient_scores_theta in
crates/polypus-optimizers/tests/adam.rs (the default, the finite
difference and an Arc of each agree with value_and_gradient), by the
adam_* tests in crates/polypus-orchestration/src/dispatch.rs (the rule
reaches the optimizer, one batch of 2·dims + 1 per iteration and the
final θ) and in src/walltime.rs (the projection counts the batches
sent for every combination of gradient and minibatch, one or two per
iteration, the same batches with and without the watch, the watch of an
iteration with an exact gradient, a forwarded value_and_gradient timed
as a batch, whose one-call iteration the projection times exactly, and a
forwarded scores_theta). Through Python, tests/python/test_adam.py
pins the batches at the seam (one batch of θ and its stencil per
iteration, then the final θ, with each rule), the configuration and an
unknown rule rejected before any batch, the defaults, and both entry
points; the Adam cases of tests/python/test_oracle_contract.py cover a
bad value in a batch, the updated θ's own and the final θ's included.
- SPSA (AlgorithmSPSA, exposed as polypus.SPSA: Spall's
simultaneous perturbation stochastic approximation, ascending the fitness,
with a calibrated first step).
- Preconditions, each an OptimizerError::InvalidConfig before any RNG draw
or oracle call, in this order: max_iters >= 1, dimensions >= 1,
resamplings from 1 to AlgorithmSPSA::MAX_RESAMPLINGS (2³¹ − 1, so an
iteration's batch of 2·resamplings + 1 fits in u32, as CMA-ES's
population must), perturbation and target_step finite and > 0,
alpha in (0.5, 1], gamma > 0 with alpha − gamma > 0.5 (Spall's
conditions on the gains), stability_constant finite and >= 0,
eval_interval >= 1, then initial_point as under Starting point
above.
- θ₀ is initial_point when given, otherwise drawn uniformly from
[0, 2π); the iterates are not wrapped. The first call is the
calibration: one evaluate_batch of 50 candidates, 25 pairs
[θ₀ + c·Δᵢ, θ₀ − c·Δᵢ] with ±1 perturbations Δᵢ and c the
perturbation. Each pair gives |f₊ − f₋|/(2c), the magnitude of every
component of its gradient estimate; the first gain is
a₁ = target_step / mean, the mean over the pairs whose magnitude is
finite (a non-finite value, or an overflow, leaves its pair out), and
a = a₁·(1 + A)^α with A the stability_constant, so the first step
does not depend on A (exactly a = a₁ with the default A = 0). With
no such pair, a zero mean (a flat landscape), a non-finite mean or a
non-finite a₁, a₁ = target_step and a warning is logged; the run goes
on.
- Iteration k = 1, …, max_iters makes one evaluate_batch, its length
checked: K = resamplings fresh pairs [θ_k + c_k·Δ, θ_k − c_k·Δ],
2K candidates, headed by θ_k itself (2K + 1) on the first
iteration and every eval_interval iterations after it. It steps
θ_{k+1} = θ_k + a_k·ĝ_k with a_k = a/(k + A)^α, c_k = c/k^γ and ĝ_k
the mean of the pairs' estimates (f₊ − f₋)/(2c_k)·Δ whose slope
(f₊ − f₋)/(2c_k) is finite; with none, θ stays. After the last step,
one evaluate_batch of one candidate, its length checked, measures the
θ it reached, so the last iteration's pairs feed a measured step.
- best_params is the measured θ_k with the best fitness and
best_fitness the value the oracle returned for it (the perturbed
candidates never count), kept as Adam's: the first measurement, then only
a strictly better one, so a NaN never wins over a number.
fitness_history[k − 1] is the best measured up to iteration k, the
final θ counted in the last entry; the first iteration measures θ₀, so
no entry is the -∞ placeholder (a NaN measurement can appear), and
the last is best_fitness.
- No early stop: the run makes max_iters iterations and reports
converged = false, as QNG does.
- The gains use powf, so a seeded run reproduces on the same platform and
build only, as CMA-ES's (C-7).
- In a training run the calibration is a leading batch of the CUNQA
walltime projection (RunShape::leading_batches): it is not timed, and
its circuits count as iterations at the first iteration's pace. The
final θ counts as one more iteration, a bound on its single candidate.
The first iteration measures θ, 2K + 1 circuits where most iterations
have 2K, so on Q QPUs the projection stays an upper bound but can
reach ⌈(2K + 1)/Q⌉ / ⌈2K/Q⌉ of the real time: (2K + 1)/2K on one QPU
(1.5× with K = 1), 2× on 2K QPUs, 1× on 2K + 1 or more.
- Enforced by crates/polypus-optimizers/tests/spsa.rs (the calibration
batch and the first step it sets, the stability constant keeping it and
slowing the decay, the flat and non-finite fallbacks and a non-finite
pair left out; one batch of 2K per iteration with θ first
when measured, then the final θ alone; every step against Spall's
recurrence, the last included; the C-5
postconditions against the batches the oracle saw over 25 seeds, with one
and several perturbations; convergence on a sphere and a periodic cosine;
seeded reproducibility; a NaN measurement, a non-finite estimate and an
oracle of only NaN; every rejected configuration with no oracle call;
the oracle's length check, the final θ's included; and a single
iteration, which steps and measures where it lands), the unit tests in
src/spsa.rs, the spsa_* tests in
crates/polypus-orchestration/src/dispatch.rs and
spsa_run_shape_counts_the_batches_the_optimizer_sends with
the_spsa_calibration_is_not_timed_as_the_first_iteration in
src/walltime.rs. Through Python, tests/python/test_spsa.py pins the
calibration and the batches at the seam, the final θ included, the
pairs centred on θ, the first two steps with and without a stability
constant, the
configuration rejected before any batch on both entry points, the
defaults and a native climb; the SPSA cases of
tests/python/test_oracle_contract.py cover a bad value in a batch,
θ's own and the final θ's included.
- Rotosolve (AlgorithmRotosolve, exposed as polypus.Rotosolve:
Ostaszewski, Grant and Benedetti's closed-form coordinate update, with the
value reuse of Nakanishi, Fujii and Todo's NFT, maximising).
- Preconditions, each an OptimizerError::InvalidConfig before any RNG draw
or oracle call, in this order: sweeps >= 1, dimensions >= 1,
reevaluate_every >= 1, tolerance finite and >= 0, patience >= 1,
then initial_point as under Starting point above.
- What it assumes and who checks it: every parameter is the angle of one
rotation generated by a single Pauli operator (or a phase), as ±θ + c,
and the fitness is linear in each circuit's measured distribution (a
cost per bitstring averaged over the shots, and for qml.train a mean
over the samples). Then f(θ_j + t) = a + A·cos t + B·sin t along each
parameter. The optimizer cannot see the circuit; train and qml.train
(and qml.Model.fit for a native model, C-11)
check it before anything runs (no backend, no CUNQA allocation) and
raise ValueError with the first problem: for a polypus.Circuit,
ParameterizedCircuit::check_single_frequency (polypus-circuit; the
gates rx, ry, rz, rxx, rzz, p, u1, and every angle of u,
u2 and u3, which are rz(φ)·ry(θ)·rz(λ) up to a global phase; each
parameter in exactly one angle, with coefficient exactly ±1 and no other
parameter, the coefficients computed in written order: +, − and ·
or / by a constant, any other operation on a parameter rejected); for a
Qiskit circuit, polypus_python.rotosolve (the same gates, with ryy,
rzx and the angle θ of r, not its φ, which turns the rotation's axis;
composite gates read through their definitions; in qml.train only the
ansatz's parameters trained, the feature map's being constants). Qiskit
simplifies some expressions as it builds them, so the Python check takes
a coefficient from Qiskit's derivative and then checks that the angle is
±θ + c at values of θ from −10⁶ to 10⁶, which rejects an angle that is
that only on part of the line (abs(θ), exp(log(θ))); an expression
Qiskit folds back to ±θ + c (θ·x/x, θ**1) is accepted, which the
Rust check, without simplification, rejects. qml.train also rejects a polypus.SampleCost, a function
of each sample's whole distribution. Controlled rotations are rejected,
cp and cu1 included, and so is every custom gate of a
polypus.Circuit, with or without a body, and a Qiskit gate whose
definition is missing or cannot be built.
- θ₀ is initial_point when given, otherwise drawn uniformly from
[0, 2π) (drawn either way). Step k = 0, 1, … updates parameter
j = k mod d with one evaluate_batch, its length checked:
[x + π/2·e_j, x − π/2·e_j], headed by x itself on step 0 and every
reevaluate_every steps (k mod reevaluate_every == 0). With f₀ the
value of x (measured, or else the maximum the previous step predicted)
and f± the two neighbours, a = (f₊ + f₋)/2, B = (f₊ − f₋)/2,
A = f₀ − a; x_j moves by atan2(B, A) and is wrapped into
[0, 2π), and the predicted maximum is a + hypot(A, B). A flat
coordinate (A = B = 0) does not move. When f₀, f±, the shift or
the maximum is not finite, the coordinate is left as it is; a
non-finite f₀ stays until x is measured again.
- best_params is the best of the measured points (x when measured,
and every neighbour), kept as Adam's: the first measurement, then only a
strictly better one, so a NaN never wins over a number; predicted
values never compete. The neighbours are offered unwrapped, so
best_params can lie up to π/2 outside [0, 2π), and further when an
initial_point outside it leaves a coordinate unmoved.
fitness_history[k] is the best measured up to step k; step 0 measures
θ₀, so no entry is -∞, and the last is best_fitness. After the last
step, whether the run used its sweeps or
stopped early, one more evaluate_batch of one candidate, its length
checked, measures the point it reached; it competes for best_params
like any measured point and its value joins the last entry of
fitness_history. The stop is decided before it, so that entry can be
higher than the one the stop judged.
- Stopping in whole sweeps (d steps): with B₀ the value measured for
θ₀ and B_s the best measured at the end of sweep s, the run stops at
the end of the sweep that makes patience consecutive sweeps with
B_s − B_{s−1} < tolerance (a larger or non-finite difference resets the
count) and reports converged = true; otherwise it runs sweeps sweeps
and reports converged = false. tolerance = 0 never stops early.
iterations_run counts steps.
- The step calls atan2 and hypot, so a seeded run reproduces on the
same platform and build only, as CMA-ES's (C-7).
- In a training run the CUNQA walltime projection counts sweeps × d + 1
steps of one batch each, the final point as a step, with no leading
batch, and its warning asks to lower sweeps. The first step measures
x, 3 circuits where most steps have 2, so on Q QPUs the projection
stays an upper bound but can reach
⌈3/Q⌉ / ⌈2/Q⌉ of the real time: 1.5× on one QPU, 2× on two, 1× on
three or more.
- Enforced by crates/polypus-optimizers/tests/rotosolve.rs (each step on
the maximum along its coordinate of a coupled sinusoid against a grid,
for several reevaluate_every; a separable sinusoid solved in one sweep;
a flat landscape that never moves; one batch of 2 per step with x first
when measured, then the final point alone, where the last step moved;
the C-5 postconditions against the batches the oracle saw
over 25 seeds; seeded reproducibility; patience counted in sweeps, a
reset by an improving sweep and by a NaN improvement; a NaN for x,
a NaN beside it, an infinite value and an oracle of only NaN; every
rejected configuration with no oracle call and their order; the oracle's
length check), the unit tests in src/rotosolve.rs (the closed form
against a brute-force maximisation of 500 random sinusoids and against
the paper's minimising form), crates/polypus/tests/rotosolve_statevector.rs
(exact statevector expectations of a native circuit with every accepted
gate: each step on the maximum; a controlled rotation, which the check
rejects, makes it miss), the single_frequency tests in
crates/polypus-circuit, the rotosolve_* tests in
crates/polypus-orchestration/src/dispatch.rs and src/walltime.rs, and
tests/python/test_rotosolve.py (the Qiskit check, the ValueErrors
before the CUNQA seam is reached on both entry points, the batches at the
seam, invalid settings before any batch, the defaults and a native
climb); the Rotosolve cases of tests/python/test_oracle_contract.py
cover a bad value in a batch, the re-measured x included.
- External (AlgorithmExternal, exposed as polypus.External: a bridge
to an optimizer outside Polypus through the AskTell trait, ask() for a
batch and tell(candidates, values) for its values, maximising; the
bindings implement it over any Python object with those two methods, and
polypus.ask_tell adapts Optuna, Nevergrad and pycma, #399; an
adapter's tell raises ValueError for other candidates than the batch
it handed out, and Optuna's adapter has close(), which marks the trials
of an untold batch failed).
- Preconditions, each an OptimizerError::InvalidConfig before any ask
or oracle call, in this order: max_evaluations >= 1,
dimensions >= 1; initial_point is refused (under Starting point
above). polypus.External checks, when it is built and when either
attribute is set, that max_evaluations is an integer from 1 to
2⁶⁴ − 1 (ValueError out of that range, TypeError for a value that is
not an integer, a bool or a float included) and that optimizer has
callable ask and tell (TypeError).
- Batch k = 0, 1, … is one ask(). None or an empty batch ends the
run with converged = true. A batch of n rows with
spent + n > max_evaluations ends it with converged = false and is
neither evaluated nor told, and a run that has spent exactly
max_evaluations ends without asking again (converged = false), so
the candidates evaluated never exceed max_evaluations. Otherwise every
row is checked, exactly dimensions values and every one finite (the
first that is not is OptimizerError::InvalidCandidate { batch, row,
reason }, with nothing of that batch evaluated or told), the batch is
one evaluate_batch, its length checked (OracleLengthMismatch,
and that batch is not told), and tell receives exactly those rows and
the oracle's values, in order. In Python a row or a batch that is not
iterable, or a value that is not a real number (a bool or a NumPy
bool_, a complex number, an int too large for a float, anything
float() refuses), is a ValueError with the same wording, raised by
the conversion before the bridge sees the batch; a batch is read only up
to one row past the budget left, so an endless iterator ends the run as
any batch over the budget does, a row only up to one value past
dimensions, so an endless row is a row too long (it has more than d
values), and a pending Ctrl+C is checked before each row. External
takes part in Python's garbage collection (__traverse__ and
__clear__ of its optimizer), so an optimizer that holds its External
is freed with it.
- A first ask() that proposes nothing (OptimizerError::ExternalOptimizer)
and a first batch larger than max_evaluations (InvalidConfig for
max_evaluations) are errors before any oracle call: nothing was
measured, so there is no result. Both, and InvalidCandidate, are
ValueError in Python. An error from ask or tell is
ExternalOptimizer with its message; through Python the original
exception is raised instead (C-1).
- best_params is the best measured candidate, kept with
BestMeasured in batch order (the first measurement, then only a
strictly better one, so a NaN never wins over a number), and
best_fitness the oracle's value for it, whatever the library reports
as its own best. fitness_history[k] is the best measured up to batch
k, so the last is best_fitness; iterations_run counts the batches
evaluated and told.
- No seed: the library owns its randomness and its start (C-7).
Method::final_candidates() is 5. In a training run the CUNQA walltime
projection counts ⌊max_evaluations / n⌋ batches after a first batch of
n candidates (at least one): exact when every batch has the first's
size, an upper bound to within one first batch when they grow (if a
batch k times larger takes at most k times as long), and possibly
too low when they shrink. The first batch is timed until the second
starts, so the library's tell() and next ask() between them are in
the projection; a run of one batch is not projected. Its warning asks to
lower max_evaluations (docs/backends.md).
- Enforced by crates/polypus-optimizers/tests/external.rs (one oracle
batch per ask and its values told; None and an empty batch; a batch
over the budget neither scored nor told; the budget spent exactly and
never exceeded over several batch patterns; a first ask with nothing
and a first batch over the budget, with no oracle call; rows of the
wrong length, NaN and ±∞, with no oracle call; failing ask and
tell; the oracle's length check; the configuration rejected before any
ask; the C-5 postconditions against the batches the oracle saw over 25
seeds and three batch patterns; a NaN never winning; a deterministic
run), the unit tests in src/external.rs, the external_* tests in
crates/polypus-orchestration/src/dispatch.rs and src/walltime.rs
(an_external_run_is_projected_from_its_first_batch among them),
final_candidates_counts_five_for_population_and_external_methods_and_one_for_local_ones
in src/final_batch.rs, the flow tests of every method in src/flow.rs,
the unit tests in crates/polypus/src/bindings/external.rs (the
conversions, bools, complex numbers and huge integers refused, a batch
read up to one row past the budget and a row up to one value past
dimensions, the recorded exception class, the configuration checks),
method_is_send_and_sync in
crates/polypus-orchestration/src/dispatch.rs,
tests/python/test_external.py (the object, the ValueErrors before
the seam is reached, one batch per ask on train and qml.train, the
budget, the rows, an endless row, the exceptions, the calling thread,
reuse, the spread over the QPUs, a reference cycle collected, and the
outcome against what tell received over 5 seeds), and
tests/python/test_ask_tell_adapters.py (the adapters against fakes of
each library's public API, their tell refusing other candidates than
the batch handed out, Optuna's close() failing an untold batch's
trials, the pip extras' floors against CI's pins, and through the bridge
with Optuna's TPE, Nevergrad and pycma, their values negated for the
minimising ones, and Optuna's close() on a real study: these skip when
a library is not installed, but CI installs the three, pinned, on its
latest Python and sets POLYPUS_REQUIRE_EXTERNAL_LIBRARIES=1, so there
they run); the External cases of
tests/python/test_oracle_contract.py cover a bad value in a batch,
which the library is not told.
- Minibatches (batch_size). With a minibatch, evaluate_batch scores a
per-call subset of the training samples, and the run's Oracles also carry
full_evaluation, the same model on every sample. The search steers by the
subsets; what is reported is the full dataset:
- Adam: the minibatch drives only the gradient. Adam's own oracle is
full_evaluation, so each iteration scores θ on every sample and then
asks for the gradient on the minibatch: two calls. A
FiniteDifferenceGradient of the minibatch is used without its
value_and_gradient, since its θ would be a minibatch value; an exact
gradient does not score θ. fitness_history and best_fitness are
therefore full-dataset values and every postcondition above holds, and the
walltime projection counts the two calls.
- DE, PSO, CMA-ES, QNG, SPSA, Rotosolve and External: every evaluation
is a minibatch estimate, so after the run best_fitness is re-scored on
every sample for the returned best_params. fitness_history keeps the estimates the search used, so its
last entry need not equal best_fitness: the one exception to the
quality-trajectory rule.
- The final batch (final_shots) scores every sample too: the native QML
oracle's evaluate_batch_with_shots draws no minibatch, so a seeded run
is the same up to it.
- Enforced by the a_minibatched_* tests in
crates/polypus-orchestration/src/dispatch.rs, the minibatch cases of
adam_run_shape_counts_the_batches_the_optimizer_sends in
src/walltime.rs, and the minibatch and factory tests in
crates/polypus-evaluation/src/qml_oracle.rs (with
a_native_final_batch_scores_every_sample_with_its_shots), and, through
qml.Model.fit, the minibatch cases of
tests/python/test_qml_native_initial_point_final_shots.py (Adam and DE:
the run unchanged, and the final value on every sample, not on a
minibatch).
Enforcing test: invariant test with multiple seeds in
crates/polypus-optimizers/tests/ (the pure-Rust optimizer↔oracle invariant),
plus the DE fitness-stagnation tests there
(de_early_stops_on_fitness_stagnation, de_large_patience_never_stops_early)
and the fitness_stagnated unit tests in crates/polypus-optimizers/src/util.rs,
plus tests/python/test_oracle_contract.py for the Python-backed length and
finiteness guarantee: the Rust invariant test never exercises the Python-callback
return path, so it covers only one half of the contract. The Python test forces a
short return list and a non-finite value through polypus.train and asserts each
surfaces as a typed polypus.EvaluationError (naming both lengths, or the
offending index/value), never a pyo3_runtime.PanicException and never a
silently-poisoned result.
The DE strategies have their own suite,
crates/polypus-optimizers/tests/de_strategies.rs: the pinned "rand1bin"
outcome (rand1bin_default_matches_its_pinned_outcome, re-pinned in #410),
j_rand (rand1bin_never_evaluates_a_trial_equal_to_its_parent), the seam
(an_optimum_on_the_seam_converges_as_well_as_one_at_pi), F and CR
(rand1bin_uses_the_given_mutation_factor_and_crossover_rate,
invalid_rates_are_rejected_before_any_evaluation), the multi-seed
invariant (adaptive_strategies_best_params_fitness_invariant_holds_across_seeds),
the stagnation stop, length errors (one on a shrunken L-SHADE batch), the
L-SHADE schedule and budget
(lshade_spends_the_budget_in_more_and_smaller_generations) and the
population edge cases. In polypus-orchestration,
de_strategy_reaches_the_optimizer checks the wiring and
de_run_shape_counts_the_batches_the_optimizer_sends that the walltime
projection counts exactly the batches each strategy sends;
tests/python/test_de_strategy.py checks the ValueError and the batches
each strategy sends, test_seed_reproducibility.py the seeded runs, and
test_oracle_contract.py runs with every strategy.
C-6 · Version coherence¶
The workspace Cargo.toml version ([workspace.package].version) is the
single source of truth. It is X.Y.Z in a release and X.Y.Z-dev on
main between releases (docs/RELEASING.md). Everything else follows it:
- a release tag
vX.Y.Z(never for a-devversion); - the version pin of every internal crate in
[workspace.dependencies], exactly; - the root
versionofCITATION.cff: equal in a release; on a-devversion it keeps the last release, so it must be an earlierX.Y.Z; - the version of the installed
polypus-quantumdistribution, which maturin derives from it at build time (X.Y.Z-devbecomes the PEP 440X.Y.Z.dev0); polypus.__version__, astrthe compiled extension sets fromCARGO_PKG_VERSIONwhen it is built, in the same PEP 440 form as the distribution, so it names the binary actually loaded rather than whatever distribution metadata happens to be installed, and a build ofmainnever reports a released version. It is listed inpolypus.__all__.
The release workflow refuses to publish when the tag and Cargo.toml diverge.
Historical note: tag and Cargo.toml diverged at 0.6.0 (see CHANGELOG). The coherence check is enforced from 0.7.0 onwards; aligning the workspace version is the first release action.
Enforcing checks:
- Tag, pins,
CHANGELOG.mdandCITATION.cff↔Cargo.tomlat release: thegatejob of.github/workflows/release.yml(.github/scripts/release_check.py, tests in.github/scripts/test_release_check.py), on every tag push and manual run withtarget=pypi. - Version form, internal pins and no already-tagged
X.Y.Zon every pull request and push tomain: the same script in branch mode, from.github/workflows/hygiene.yml. Cargo.toml↔CITATION.cff:.github/workflows/hygiene.ymlon every pull request and push tomain(.github/scripts/hygiene.py, ruleversion-mismatch; tests in.github/scripts/test_hygiene.py).polypus.__version__↔Cargo.toml↔ installed distribution:tests/python/test_version_coherence.py, in the CI Python suite against the installed wheel. Its distribution comparison skips only when nopolypus-quantumdistribution is installed, and itsCargo.tomlcomparison only when the tests run outside the repository.
C-7 · Seeding & run manifest (Python entry points)¶
This contract governs the outer Rust↔Python boundary of the public entry
points polypus.run_quantum_circuit, polypus.train, polypus.qml.train and
polypus.qml.predict, and of the native QML API's Model.fit,
TrainedModel.predict, TrainedModel.run, polypus.qml.expval,
polypus.qml.jacobian and polypus.qml.vjp, and polypus.torch.QuantumLayer
over them (C-11):
their seed kwarg and their return shape. (It is distinct from C-1, which
freezes the internal run_qcs seam to the polypus_python package.)
The seed kwarg¶
run_quantum_circuit(..., seed: int | None = None)seeds shot sampling across every simulated backend:- With
infrastructure="local"(backend="polypus", the native statevector simulator, orbackend="aer", Qiskit Aer): an explicitseedis used directly — the native backend seeds its own RNG in-process, and Aer receives it as theseedkwarg forwarded across the C-1 seam (crates/polypus-infrastructure/src/local.rs, which passes it to Aer'sseed_simulatoroption inpolypus_python'slocal.py) — and reproduces the counts byte-for-byte across calls, verified against a real Aer install.seed=Nonedraws a fresh seed from OS entropy, so repeated calls produce independent noise (never the run-id-derived repetition that motivated this contract). The runidis decoupled from the RNG — it is only a logging/temp-file/SLURM label. - Seed range (#393). Aer's
seed_simulatoris a signed 64-bit integer, so the backends that run on Aer —backend="aer"and CUNQA's simulated QPUs — take a seed from0to2**63 - 1; the native backend and a registered backend (the subprocess bridge, a third party's) take any 64-bit seed. A seed drawn from OS entropy is always below2**63, on every backend, so the seed a run reports is the one Aer receives on the run's first call (and CUNQA on QPU 0 of it): a run of one call, such as arun_quantum_circuitwithn_qpus=1, replays outside Polypus withAerSimulator(seed_simulator=seed); later calls get derived seeds (below). An explicit seed of2**63or more on an Aer path raisespolypus.ConfigurationError(aValueError) before any backend is built (BackendConfig::check_seed, called by every entry point this contract lists); until #393 it reached Aer masked to 63 bits, so two seeds that differed only in bit 63 gave the same counts. The 63-bit mask inlocal.pyandcunqa.pystill applies to the seeds Polypus derives: the per-call seeds below and CUNQA's per-QPUseed + k. Enforcing tests:tests/python/test_seed_range.py(every entry point),test_a_seed_of_two_to_the_63_or_more_is_rejected_before_any_qpuintests/python/test_cunqa_run_flow.py, and thecheck_seed/random_seedtests incrates/polypus-infrastructure/src/execution_config.rs. - Per-circuit seeds (native backend). A native backend seeded with
snumbers the circuits it runs0, 1, 2, ...(a global counter across the batches it executes, reserved as one contiguous block per batch) and seeds circuitkwithcircuit_seed(s, k): outputkof a SplitMix64 stream whose state starts at SplitMix64-mixeds(crates/polypus-infrastructure/src/native.rs). Distinct circuits in a batch and distinct base seeds therefore get unrelated streams; in particular circuitkof seedsis not circuitk-1of seeds+1, so repetitions with seeds0, 1, 2, ...are independent. The seed of a circuit depends only on(s, k), never on chunking, the memory cap or gate-vs-circuit parallelism. Shot splitting acrossn_qpusreplicas gives replicaiseed indexiof the batch, so the single-evolution fast path reproduces the per-replica counts of running the replicas one by one. Until #348 the seed wass + k, which made neighbouring base seeds share streams shifted by one circuit; counts for a fixed seed changed when that was fixed. Aer and CUNQA receive one seed per call instead (see The seed across the calls of one run): arun_quantum_circuitthat is one call gives Aer the base seed unchanged, and CUNQA adds its per-QPU offset below. - With
infrastructure="cunqa": the sameseedkwarg is forwarded across the same seam (crates/polypus-infrastructure/src/cunqa.rsmirrorslocal.rs,polypus_python'scunqa.pymirrorslocal.py), with a per-QPU offset so distributed shots aren't identical copies: the circuit sent to QPUkruns with the call's seed (below)+ k, masked to 63 bits (so2**63 - 1 + 1wraps to0; the base seed itself is below2**63, see the seed range above). With shots split across the QPUs, replicairuns on QPUi, so every replica gets its own QPU and seed even when the split is uneven (shotsnot a multiple ofn_qpus) and is sent as onerun_qcscall per batch size, each carrying its first replica's index asqpu_offset(C-1; fixed in #370).tests/python/test_cunqa_run_flow.pypins the seeds, the counts shape and reproducibility end to end against a fake CUNQA, and the opt-intests/python/test_cunqa_real.pychecks that a seed reproduces and that QPUs differ on a real family (#357; passed on CUNQA 3.0.0). - With physical hardware (
infrastructure="qmio"): passing an explicitseedraisesValueError. Real quantum processors rely on physical processes and cannot be deterministically seeded, so silently accepting a seed would give false confidence in reproducibility.seed=Nonebehaves exactly as before. train(..., seed=None)/qml.train(..., seed=None)seed the optimizer's RNG and are always accepted, for every backend, within that backend's seed range (see Seed range above: on Aer and CUNQA a seed of2**63or more, from the kwarg or from the optimizer'sseedfield, is apolypus.ConfigurationError), because the seed's primary job (making population init / mutation deterministic, inside the pure-Rustpolypus-optimizers) is independent of which backend evaluates the oracle. Precedence: the explicitseedkwarg wins; otherwise theseedfield pinned on theDE/PSO/QNG/CMAES/Adam/SPSA/Rotosolveinstance; otherwise a fresh OS-entropy value.Externalhas noseedfield (method_seedreturns nothing for it): its library owns its randomness and is seeded where the user builds it, so the resolved seed only seeds shot sampling and is reported; with a deterministic optimizer a seeded native run reproduces exactly (tests/python/test_seed_reproducibility.py, the External cases). On the native, Aer, and CUNQA backends the resolved seed also seeds shot sampling, so atrain()run on any of them is reproducible end-to-end, in another process too: every cost reducer sums a counts map in ascending bitstring order, never inHashMaporder, which differs per process (#401;TestReplayInFreshInterpreterintest_seed_reproducibility.pyreplays seeded native runs in fresh interpreters);qml.trainis Qiskit/Aer-only (native rejected), and since Aer shot noise is now seeded too, its reproducibility guarantee covers both the optimizer trajectory and Aer's sampling. A seededCMAESrun reproduces on the same platform and build only: its steps callexp,lnandcosfrom the platform's math library, which is not guaranteed correctly rounded, so its trajectory can differ between platforms even over a platform-independent backend (DE's steps are basic arithmetic only).Adamdoes not carry that caveat: with eitherruleits steps use only +, −, ×, ÷ andsqrt, all correctly rounded in IEEE 754 (its bias corrections are running products, not powers), so a seeded run over a platform-independent backend reproduces bit for bit on every platform;crates/polypus-optimizers/tests/adam.rspins one per rule. A seededSPSArun carries CMA-ES's caveat: its gainsa/k^αandc/k^γcallpowf, which is not guaranteed correctly rounded either, so it reproduces on the same platform and build only;crates/polypus-optimizers/tests/spsa.rscompares two runs instead of pinning one. A seededRotosolverun carries the same caveat: its seed only draws θ₀, but every step callsatan2andhypot;crates/polypus-optimizers/tests/rotosolve.rscompares two runs. Withfinal_shots(C-5) the final batch is the run's last call (below), sent after every call of the optimizer, so a seeded run gives the samebest_params,best_fitnessandfitness_historywith and without it, and the final batch has shot noise of its own, which a seeded run reproduces too.qml.predict(..., seed=None)seeds shot sampling likerun_quantum_circuit: an explicit seed reproduces the counts,Nonedraws one from OS entropy, and the effective value is reported.qmiois rejected outright, since a QML model is a Qiskit circuit.Model.fit(..., seed=None)followstrain: the explicitseedwins, then the optimizer object's field, then OS entropy. The effective seed also seeds the shot sampling and the minibatch draws (one subset of the samples per oracle call, drawn from the seed and a call counter), so a run replays exactly. Withexact=Truenothing is sampled, and the seed drives only the optimizer and the minibatches. An explicitseedis an integer from 0 to 2⁶⁴ − 1: one outside is apolypus.ConfigurationErrornaming it, aboolaTypeError(C-11, Execution integers). On Aer and CUNQA the effective seed must also be below2**63(Seed range above), checked once the backend's configuration is built.TrainedModel.predict(..., seed=None)/TrainedModel.run(..., seed=None)seed shot sampling likerun_quantum_circuit: an explicit seed reproduces the counts,Nonedraws one from OS entropy, and an explicit seed onqmiois aValueError. Withexact=Truenothing is sampled. An explicitseedis an integer from 0 to 2⁶⁴ − 1, as forModel.fit, checked before theqmiorefusal (C-11), and below2**63on Aer and CUNQA (Seed range above), checked after it.qml.expval(..., seed=None)/qml.jacobian(..., seed=None)/qml.vjp(..., seed=None)followTrainedModel.run: an explicit seed reproduces the result bit for bit,Nonedraws one from OS entropy, an explicit seed onqmiois aValueError, and withexact=Truenothing is sampled. An explicitseedis an integer from 0 to 2⁶⁴ − 1, as forModel.fit, checked before theqmiorefusal (C-11), and below2**63on Aer and CUNQA (Seed range above), checked after it. They return bare arrays with no manifest, so the effective seed is only logged (with the runid, atinfo): to replay a call, pass aseed. A call runs its rows in blocks over one backend (C-11); on the native backend the circuit counter runs on across the blocks, so a seeded result does not depend on the block size. On Aer and CUNQA each block is at least one call, and the block size follows the host's cores and the backend's concurrency, so a seeded call replays on the same configuration, as aqml.traindoes (below).polypus.torch.QuantumLayer(..., seed=None)never passes itsseedon as such: forward passnof the layer callsqml.expvalwithSeedSequence([seed, n, 0]).generate_state(1, uint64)[0] & (2**63 - 1), and the backward pass of that forward pass callsqml.vjpwith[seed, n, 1]masked the same way — below2**63, the seed range of Aer and CUNQA, which until #393 masked it the same way at the seam, so a seeded layer on Aer gives the values it gave before; on the native backend the derived seeds whose bit 63 was set changed — so every backend call of a training gets its own stream, a layer rebuilt with the sameseedreplays the values and gradients step by step, and seedssands+1share no stream. The counter is the layer's, outside thestate_dict.seed=NonepassesNoneto every call, which draws and logs its own; an explicitseedonqmioisqml.expval's error at the first forward pass. Enforced bytest_torch_quantum_layer.py'sTestSeeds.- OS entropy failure. If the OS entropy source cannot be read, the entry
point raises
polypus.BackendErrorinstead of panicking — whether while drawing a default seed (seed=Noneand, fortrain/qml.train, noseedpinned on theDE/PSO/QNG/CMAES/Adam/SPSA/Rotosolveinstance, or apolypus.External) or while drawing the random bytes of the runid's UUID v4 suffix. Every call draws an id, so this holds with or without an explicit seed and forinfrastructure="qmio", which never draws a seed.
The seed across the calls of one run¶
A run (one entry-point call) sends its circuits to one backend in one or more
calls: a train sends the initial population and one batch per generation,
each split into waves when it exceeds the backend's concurrency (CUNQA:
n_qpus) or the memory budget, and qml.train also windows its candidates by
the host's cores, and qml.expval/qml.jacobian/qml.vjp their rows by the
same rule
(C-11); the final_shots batch is the last call. Every call gets
its own sampling stream, on every backend (#411), so no two calls of a run
share shot noise, and the same seed replays the whole sequence:
- The native backend seeds circuit
kof the run withcircuit_seed(s, k)(above); its calls take consecutive blocks ofk, so its seeds do not depend on how the batches are split. - Aer, CUNQA and the subprocess bridge receive one seed per call: the base
seed
son call0andstream_seed(s, n)on calln >= 1, the native map (polypus_backend::{stream_seed, CallSeeds}). Calls are numbered in the order the backend receives them, which is the run's: the planners call a backend sequentially. Everyrun_circuitscall counts, and so does arun_shots_distributedcall on CUNQA, which overrides it; Aer and the bridge use the trait's default, onerun_circuitscall per shot group, so an uneven shot split is several calls there. CUNQA adds each QPU's offset to its call's seed. A run of one call, such as arun_quantum_circuitwithn_qpus=1or an even split, therefore seeds Aer exactly as Aer's ownseed_simulator=sdoes. On that first call, as before #411, neighbouring base seeds can share streams (on CUNQA, QPUk+1of seedsis QPUkof seeds+1); later calls are mixed like the native backend's circuits. - Since a call's seed depends on its index, a seeded Aer or CUNQA run replays
on the same configuration: the same
n_qpus, and for a split that depends on them, the same memory budget and core count. - A third-party backend receives the base seed in
RunParams::seedon every call and gives each call its own stream, withCallSeedsor its own derivation (docs/backends.md).
Until #411, Aer, CUNQA and the bridge received the base seed on every call,
so batch slot i was sampled with the same random numbers in every
generation, unlike the native backend; seeded results on those backends
changed in 0.8.0. A derived per-call seed is a full 64-bit value; Aer and
CUNQA receive it masked to 63 bits (local.py, cunqa.py). Enforcing tests: tests/python/test_seed_streams.py
(the seeds Aer and the fake CUNQA receive over a train, read off the
run_qcs seam, and their replay), consecutive_calls_get_their_own_streams
in crates/polypus-infrastructure/src/native.rs,
crates/polypus-subprocess-backend/tests/seed_streams.rs (the seeds the
reference worker receives) and the CallSeeds tests in
crates/polypus-backend/src/seed.rs.
The run manifest (return shapes)¶
run_quantum_circuitreturns aRunResultexposing:counts(the C-3 payload — always alist[dict], one dict per QPU replica, lengthn_qpus),merged_counts(dict, the key-by-key sum ofcountsover allshots; see C-3),id(str),seed(int | None; the effective seed used, orNoneonly for theqmioinfrastructure),backend(str),infrastructure(str).qml.predictreturns the sameRunResult, butcountsis always alist[dict], one C-3 dict per row ofxin row order:n_qpusspreads the rows, never one row's shots.merged_countsisNone: the rows are distinct circuits, so there is no meaningful total.seedis always anint;idis generated internally (predict_<n_qpus>_<infrastructure>_<uuid>).-
train/qml.trainreturn aTrainResultexposing the full optimization outcome —best_params(list[float]),best_fitness(float),iterations_run(int),converged(bool),fitness_history(list[float]),stop_reason(str, the snake_case name of what ended the optimizer's loop) andn_evaluations(int, the candidates scored as a fitness, asTrainProgress.evaluationscounts them, plus the re-score ofbest_paramsunder a minibatch; the shifted circuits of an exact gradient and the final batch not included) — and the final re-evaluation,final_params(list[float] | None) andfinal_fitness(float | None), bothNonewithoutfinal_shots(C-5), plusseed(int, the effective seed used) andid(str, the effective run id: the caller-suppliedidprefix suffixed with a UUID v4 for uniqueness — a label for logging / SLURM / temp-file identification only, never for correlating runs by content; see #75). This replaces the former barelist[float], which discarded fitness, iteration count and the convergence flag. -
Model.fitreturns the sameTrainResult.TrainedModel.runreturns aRunResultshaped likeqml.predict's (one C-3 dict per row,merged_countsNone,idgenerated asqml_<n_qpus>_<infrastructure>_<uuid>,seedNoneonly onqmio), or, withexact=True, anExactResult:probabilities(one dict per row, keyed like the counts),id,backendandinfrastructure, and noseed, since nothing was sampled.
The effective seed on both result types is what lets a caller log a run and
replay it exactly. A run started from an initial_point (contract C-5) replays
only with the same point too: the result does not echo it, so a caller that
passes one logs it alongside the seed.
Enforcing test: tests/python/test_seed_reproducibility.py (public-API
end-to-end: native and Aer reproducibility, entropy variation, the qmio
rejection, and the returned manifest/outcome fields), tests/python/test_qml_predict.py
(the qml.predict manifest, seed replay and per-row counts),
tests/python/test_qml_native_training.py and test_qml_native_inference.py
(Model.fit and TrainedModel.run: seed replay, exact runs independent of
shots, the qmio rejection, the RunResult/ExactResult fields),
test_qml_native_expval_jacobian.py's TestBlocksAndSeeds (qml.expval and
qml.jacobian: seed replay, another seed differs, an omitted one is drawn, the
qmio rejection), test_qml_native_vjp.py (qml.vjp: with a seed, the
contraction of qml.jacobian's result with that seed; another seed differs; the
qmio rejection) and a_seeded_native_result_does_not_depend_on_the_block_size
in crates/polypus/src/bindings/qml.rs, the minibatch draws in
crates/polypus-evaluation/src/qml_oracle.rs
(a_minibatch_is_drawn_once_per_call_and_shared_by_the_whole_call),
tests/python/test_determinism_baseline.py (seeded results pinned bit for bit:
counts and a mocked-backend qml.train on any platform, native train
trajectories on the fixture's build only, opt-in with
POLYPUS_DETERMINISM_STRICT=1, and the same trajectories replayed in a fresh
process on every CI leg, #407), plus the Rust tests in
crates/polypus/src/bindings/run.rs (native seed round-trip through
run_quantum_circuit, the qmio rejection path) and
crates/polypus/src/bindings/seeds.rs (the seed-resolution precedence /
optimizer determinism, the default-seed entropy-failure path
(seed_or_entropy, resolve_optimizer_seed), and the run-id entropy-failure
path and id format (unique_id_from)), crates/polypus/src/exceptions.rs
(the entropy-failure polypus.BackendError mapping),
crates/polypus-infrastructure/src/execution_config.rs (the fallible draws
random_seed_from / random_id_bytes_from and their error messages) and
crates/polypus-infrastructure/src/native.rs (same-seed reproduces /
omitted-seed differs at the backend level). CUNQA's
seed forwarding follows the same shape as Aer's on the Rust side
(crates/polypus-infrastructure/src/cunqa.rs mirrors local.rs) and is pinned
end to end against a fake CUNQA SDK by tests/python/test_cunqa_run_flow.py
(per-QPU seeds, 63-bit mask, same seed reproduces, reported seed replays). The
cunqa package isn't installed in CI; the opt-in
tests/python/test_cunqa_real.py checks the same on a real family and passed
on CUNQA 3.0.0.
C-8 · qml.train row/dimension/label symmetry (Python entry point)¶
polypus.qml.train composes a Qiskit feature_map with an ansatz, pre-binds
each row of x_train to the feature-map parameters, and hands the resulting
circuits to the optimizer, which searches a dimensions-wide vector and binds
it to the ansatz's free parameters. Two shape agreements must hold, and both are
validated upfront with a clear ValueError — before any circuit is composed
or executed — rather than surfacing as a silent truncation or a cryptic Qiskit
binding error deep inside the oracle. A third agreement governs the optional
labels.
- Row width. Every row of
x_trainmust have exactlylen(feature_map.parameters)elements. A longer row would silently drop the extra features (the pre-binding zip stops at the shorter iterator); a shorter row would leave feature-map parameters unbound and fail later as a cryptic Qiskit error inside the oracle. Either case is aValueErrorreporting the offending 0-based row index and both lengths (row features vs.len(feature_map.parameters)), consistent with howx_trainis indexed as an array/list on the Python side. -
Dimensions.
dimensionsmust be exactlylen(ansatz.parameters). This mirrorstrain, which validatesdimensionsagainst the circuit's free parameter count (circuit_source.num_params()); that symmetry was documented only implicitly (intrain's docstring) and was missing entirely fromqml.train, which is precisely why it now earns an explicit contract. A mismatch is aValueErrornaming bothdimensionsand the ansatz's free parameter count. -
Labels.
y_train(keyword-only, optional) holds exactly one label perx_trainrow, in row order, because the oracle pairs circuits with labels by position; a mismatch is aValueErrornaming both counts. Each label is a single finite real number: astr, a complex number (Python's or NumPy's, whatever its imaginary part, refused by its type beforefloat()could drop that part), another non-number or a nested row (one-hot, column vector) is aTypeError, andNaN/infaValueError, each naming the 0-based index. All-integer labels reach the objective asint, otherwise all asfloat. With labels,expectation_functionmust be a callable(bitstring, label) -> float, apolypus.CachedCost(callable)or apolypus.SampleCost((counts, label) -> float); aQubo/Isingis aTypeError, and so is aSampleCostwithout labels. These checks run before any backend is created.y_train=Noneis the unsupervised path, unchanged.
Inference (polypus.qml.predict). The same agreements hold, so a model runs
the circuit it was trained as: each row of x has exactly
len(feature_map.parameters) values (the row-width ValueError, naming x),
and params has exactly len(ansatz.parameters) finite values. An empty x is
rejected too, all before anything runs.
A row whose length cannot be read (e.g. a generator with no __len__) is a
legitimate type error and propagates as-is; it is not masked into the messages
above. y_train itself is only iterated, so a generator is fine there.
A polypus.qml.Encoder or Ansatz as feature_map or ansatz is a
TypeError before anything runs: native models are trained with
polypus.qml.Model.fit (C-11).
A Qiskit failure while composing the circuits or binding a row (an ansatz wider
than the feature map, a feature value Qiskit rejects) is raised as
polypus.EvaluationError with the Qiskit original as __cause__ (C-1, issue
218).¶
Enforcing test: tests/python/test_qml_train_validation.py (every rejection,
with nothing executed, NumPy's complex labels included), the extract_labels_*
unit tests in crates/polypus/src/bindings/extract.rs (the label checks, a
complex label included), tests/python/test_qml_supervised.py (each sample's
counts meet its own label; the objective calling convention) and
tests/python/test_qml_predict.py (the inference agreements) and
tests/python/test_qml_native.py (native pieces rejected by both).
C-9 · id charset validation (train / qml.train Python entry points)¶
The id kwarg of polypus.train and polypus.qml.train is a caller-supplied
prefix: the entry point appends a UUID v4 to it and the result becomes
ExecutionConfig::id (and the RunParams::id derived from it), which names the
run's temp files and log streams and —
on infrastructure="cunqa" — travels to SLURM as the C-1 kwargs family_name
(connect_to_infrastructure) and family_id (run_qcs), and from there
verbatim into qraise. The crate cannot see how qraise/SLURM interpolate that
name, so the string is constrained at the boundary instead of trusted:
- Charset. Every character must be an ASCII letter, an ASCII digit,
.,_or-(i.e.^[A-Za-z0-9._-]+$). Whitespace, path separators (/,../) and shell metacharacters (;,|,`,$,&, newline) are rejected. TheValueErrornames the offending character so the caller can see which one failed. - Non-empty. An empty
idis rejected: it would degrade the effective id to a bare_<uuid>and carries no debugging value. - Length. At most 64 characters, measured on the caller-supplied prefix before the UUID suffix, keeping the effective id inside the limits SLURM job names and filesystem path components impose.
This is defense-in-depth, not a fix for a known exploit — the July 2026
technical audit (#89) found the value unvalidated anywhere in the crate, which
docs/ENGINEERING.md §8 ("validate and sanitize all inputs; never trust
external data") does not allow for a string that leaves the process.
When it is checked. Upfront, alongside the other kwarg guards
(validate_shots_and_qpus, validate_cunqa_allocation) as the entry point's
first statements — before any seam call, any backend creation and, crucially,
before unique_id appends the UUID, so a rejected id never yields a
partially-valid effective id. Validation is unconditional: unlike
nodes/cores_per_qpu it is not gated on infrastructure == "cunqa", because
the temp-file and log-stream naming applies to every infrastructure.
run_quantum_circuit is not covered: it generates its own id internally and
takes no such kwarg.
Python mirror¶
The polypus_python helpers in python/polypus_python/running_functions.py also turn
an id into file names (circuit_<id>.qpy, polypus_python_<id>.log). They are
public and can be called without going through train/qml.train, so they
validate id themselves with validate_id, a Python mirror of the Rust check.
The policy is identical: same charset (ASCII letters, ASCII digits, .,
_, -, checked character by character, never with str.isalnum() or a
$-anchored regex), same 64-character bound and same order of checks (empty,
then charset, then length), with the same ValueError messages (the offending
character and the id are shown with Python's repr). A non-str id raises
TypeError.
It runs as the first statement of get_logger, log_message,
_get_temp_directory, serialize_quantum_circuit,
and _deserialize_quantum_circuit, before any filesystem access and any try
block, so a rejected id touches nothing and the log_message calls in the
error handlers can never raise on id and mask the original exception.
Enforcing tests: tests/python/test_id_validation.py (Rust entry points);
tests/python/test_python_helpers_hygiene.py (Python mirror: it reuses
the same VALID_IDS/INVALID_IDS lists, so the two sides cannot drift without
a test failing).
C-10 · OpenQASM 3 profile with Qiskit phase conventions¶
ParameterizedCircuit::from_qasm3 / to_qasm3 / to_qasm3_with_params
(Python: Circuit.from_qasm3, Circuit.to_qasm3(params=None),
Circuit.param_names) read and write the OpenQASM 3 profile with Qiskit
phase conventions — never "a subset of OpenQASM 3": the straight-line part of
OpenQASM 3.0 that carries a parameterised, terminal-measurement circuit. Its
stdgates.inc is the one of tag spec/v3.1.0
(c717508162a0eac892fa32134716fe77a284e835), whose gate list is that of
spec/v3.0.0 (51c36946c687c8b17000962f6ce735ca1d1c9b3b) with pow(1/2)
written pow(0.5).
Accepted. OPENQASM 3; or OPENQASM 3.0; (optional, first); include
"stdgates.inc";, provided internally — no file is ever read; qubit[n],
qubit, bit[n], bit declarations, flattened in declaration order;
input float[64] name; and input float name; (both binary64); calls of U,
of the stdgates.inc gates and of earlier gate declarations (bodies of gate
calls only); barrier; measurements c[i] = measure q[j];, c = measure q;,
measure q -> c; (C-4 applies unchanged); angle expressions over the inputs
(in a body, over the gate's parameters): numbers, pi/π, tau/τ,
euler/ℇ, + - * /, unary minus, ** (right-associative, binding tighter
than unary minus), and sin cos tan arcsin arccos arctan exp log sqrt;
Unicode identifiers; // and /* */ comments.
Rejected, each as CircuitError::Parse naming the construct and its
1-based line (a construct both dialects reject is worded as the OpenQASM 2.0
importer words it, so benchmarks/qasm_coverage.py classifies either):
other versions and includes;
if/else, for, while, switch; reset; classical types other than
bit and input float; let; assignments other than measurement;
bit c = measure q;; const; output; casts; def; extern; the modifiers
ctrl @, negctrl @, inv @, pow @ and gphase, in bodies too; delay,
stretch, duration, box; defcal, cal, defcalgrammar; arrays,
slices, index sets, concatenation; physical qubits ($0); annotations and
pragmas; the functions mod, popcount, rotl, rotr, floor, ceiling,
pow (and sizeof, real, imag); a division whose two operands are both
integer expressions (1/2: integer division in OpenQASM 3 — write 1.0/2);
an input named like a stdgates.inc gate, included or not (input names are
kept, and the export always includes it); in a body, a call of a gate its own
parameter or qubit argument shadows.
Phase semantics. U, u2 and u3 are read and written with Qiskit's
matrices — Polypus's u, u2, u3 — a declared deviation from the
specification by exactly e^{−iθ/2} (U) and e^{+i(φ+λ)/2} (u2, u3).
Amplitudes may differ from a specification-normative reader by these global
factors; probabilities, counts and expectation values do not. This is sound
only because modifiers and gphase are rejected (under them a global phase
becomes observable); admitting either requires global-phase tracking. Every
other stdgates.inc gate follows the specification exactly. CX is read as
cx, as standard_library.rst describes it ("an alias for cx"), although
stdgates.inc defines it as ctrl @ U(π, 0, π), which under the
specification's U is controlled-(iX). That Polypus reads Qiskit's
qasm3.dumps output as Qiskit does is tested for Qiskit 2.5.2 with
qiskit-qasm3-import 0.6.0, not guaranteed for other versions. The runtime
dependencies are bounded accordingly: qiskit>=2.0,<3 and
qiskit-aer>=0.17,<0.18 in pyproject.toml.
Spellings. On import U → u, CX → cx, phase → p, cphase →
cp; on export u → U; no other name changes. A declared gate is never
recognised as a built-in by its name.
Parameters. Inputs are the free parameters, in declaration order, unused
ones included. Their names are stored in the circuit (param_names), are part
of its equality and survive clone, export and import, Unicode included;
Qiskit's name mangling (θ[0] → _θ_0_) is not reversed. A parameter without
a name is theta_<index>, or the first free theta_<index>_<k> if a named
parameter or a declared gate the circuit calls takes that name.
Numbers. Angles are evaluated in binary64, exactly the operations written,
in source order. A constant angle is evaluated at import: a non-finite result
or a division by zero is a Parse error (on the division's line); an angle of
the inputs is evaluated at binding (NonFiniteParam, DivisionByZero). Only
the final value must be finite: 1.0/exp(1000.0) is 0.0.
Canonical form. What to_qasm3 writes, and why its output is a fixed
point: to_qasm3(from_qasm3(to_qasm3(c))) is byte-identical to to_qasm3(c)
for every circuit to_qasm3 accepts.
OPENQASM 3.0;
include "stdgates.inc";
input float[64] <name>; one per parameter, in index order
gate <name>(<p>, …) <q>, … { each definition the circuit needs, once:
<statement>; callees first, in order of first use
}
qubit[<n>] q; unless n = 0
bit[<m>] c; m = clbits_width(), unless 0
<statement>; one per instruction
- Registers:
bit[m] c;is the circuit's classical width (C-2): the sum of thebitregisters an imported program declares, or the implicit register the measurements need if that is wider — written with or without measurements, sobit[2] a; bit b;becomesbit[3] c;. A circuit from the builder writes only the bits its measurements need. - Statements:
name(a, b) q[i], q[j];;barrier q;for every qubit (barrier;with none),barrier q[i], …;otherwise;c = measure q;for a full measurement when the registers have one size,c[i] = measure q[j];otherwise. Inside a definition the same, over its formal names, indented two spaces. - Numbers: the shortest decimal that reads back as the same binary64, always
with a decimal point — positional for 1e-5 ≤ |v| < 1e16 (
0.00001,1.0), scientific otherwise (1.5e-7,1.0e16); negative zero is-0.0. - Expressions:
+and-between spaces,*,/,**without; functions by name (logfor the natural logarithm), constants aspi,tau,euler; the fewest parentheses that keep the expression:**binds tightest (right-associative; its exponent may be a negation), then unary minus, then* /, then+ -(both left-associative). A negative number is written with its minus and counts as a negation. - Instructions
stdgates.inclacks are calls of these definitions (exact matrices, checked inpolypus-sim):rzz(θ)=cx; rz(θ); cx,rxx(θ)=h ⊗ h; cx; rz(θ); cx; h ⊗ h,sxdg=h; sdg; h,csx=h; cp(π/2); hon the target,cu1=cp,cu3(θ, φ, λ)=cu(θ, φ, λ, 0),u0= the identity (empty body), andrccx,rc3x,c3x,c3sqrtx,c4xas theirqelib1.incdefinitions (qasm3.rs'sHELPER_PROGRAMholds the exact text). Declared gates are printed from their definitions, never copied. - Names: an input keeps its name. A gate, register or formal name is kept if it
is a valid OpenQASM 3 identifier of at most 4096 bytes, not a keyword,
constant, function,
U,gphaseorstdgates.incgate, and not taken in its scope (inputs, then gates in order, then registers; a definition's formals avoid all of those). Otherwise it is renamed: characters an identifier cannot hold become_;g(gate),p(parameter),q(qubit argument or qubit register) orc(bit register) is prefixed if it cannot start one;_is appended to a reserved word; it is cut to 4075 bytes;_1,_2, … is appended until it is free. Names that can be kept are claimed before any is renamed, so the scheme never collides. The registers areqandc, renamed the same way when taken. - Budgets: the export fails with
CircuitError::ExportLimitrather than write a program the importer would reject (the budgets below, counted as the importer counts them), and withCircuitError::GateNotExpressible, naming the gate, for a definition it cannot write: an OpenQASM 2.0 body with a barrier, or one that would nest or expand beyond the importer's limits once itsc4x-like calls become definition calls.
OpenQASM 2.0 export of OpenQASM 3 declarations. to_qasm2 needs every
parameter bound. A declaration imported from OpenQASM 3 is printed from its
definition on one line (gate name(a,b) x,y { h x; cx x,y; }), with log as
ln, ** as ^, tau and euler as their values, numbers as above, and
names renamed by the same scheme for OpenQASM 2.0's [a-z][A-Za-z0-9_]*
(avoiding its keywords, the qelib1.inc gates, q, c and the names of
the OpenQASM 2.0 declarations re-emitted verbatim, which keep theirs). A body using arcsin, arccos
or arctan is GateNotExpressible, naming the gate (try_to_qasm2 returns
the error; the deprecated ConcreteCircuit::to_qasm2 panics there). The backends that submit
OpenQASM 2.0 — Aer and CUNQA (through polypus_python), QMIO, the subprocess
bridge — report such a circuit as unsupported (polypus.NativeCircuitError in
Python), never a panic; the native backend expands the gate and runs it.
OpenQASM 2.0 declarations are re-emitted verbatim as before (C-2), except one
named q or c, which OpenQASM 2.0's single namespace gives to the
registers: it is printed and renamed by the same scheme (c becomes c_1),
and so is every declaration whose body calls it. The export stays a fixed
point and imports to the same gates under the new name.
Budgets (each a Parse error on import; the export stays within them):
| Budget | Value |
|---|---|
Source size (MAX_SOURCE_BYTES) |
32 MiB |
Identifier, number or string (MAX_TOKEN_BYTES) |
4096 bytes |
Inputs (MAX_INPUTS) |
100 000 |
gate declarations (MAX_DECLARATIONS) |
10 000 |
Expression nodes, one expression (MAX_EXPR_NODES) |
1 000 000 |
Expression nodes, whole program (MAX_PROGRAM_NODES) |
4 000 000 |
Expression nesting as written (MAX_EXPR_DEPTH) |
64 |
Qubits, and bits (MAX_REGISTER_BITS) |
1 000 000 each |
Instructions after broadcasting (MAX_INSTRUCTIONS) |
4 000 000 |
Qubits all barriers list, barrier q; listing every qubit of q (MAX_BARRIER_OPERANDS) |
4 000 000 |
Declared-gate nesting (MAX_GATE_NESTING) |
64 |
Statements one declaration expands to (MAX_GATE_EXPANSION) |
1 000 000 |
Statements all calls of declared gates expand to (MAX_VALIDATED_EXPANSION) |
20 000 000 |
The budgets live in one module (crates/polypus-circuit/src/limits.rs), and
the OpenQASM 2.0 importer enforces them too, with the same messages (issue
343): source and token size, declarations, register size, instructions after¶
broadcasting (checked before a statement is expanded), barrier operands, at
most MAX_EXPR_NODES
nodes in one parameter list, and at most MAX_PROGRAM_NODES nodes in gate
bodies, whose expressions it keeps (top-level angles are evaluated as they are
read). It lexes the source as it parses it. The OpenQASM 2.0 export is not
budgeted: a register broadcast written out statement by statement can outgrow
MAX_SOURCE_BYTES, and such an export does not import again.
Enforcing tests: crates/polypus-circuit/tests/hardening.rs.
Rationale, evidence and alternatives considered: see
docs/adr/0004-openqasm3-profile-and-angle-expressions.md.
Enforcing test: crates/polypus-circuit/tests/qasm3.rs (every accepted
and rejected construct with its line and message, the budgets on both sides,
the canonical layout, numbers and parentheses, renaming and collisions — a
native and a declared rzz included —, cross-dialect export),
crates/polypus-circuit/tests/contracts.rs (c2_*qasm3*: the vocabulary's
fixed point, and the declared bit width), the declared_clbits_* tests of
crates/polypus-circuit/tests/qasm3.rs (the width written as bit[m]),
crates/polypus-sim/tests/qasm3_semantics.rs (full matrices:
every stdgates.inc gate and U against the specification, U/u2/u3 by
the declared factors, CX, every exported definition, cross-dialect),
tests/python/test_qasm3.py and tests/python/test_qasm3_interop.py (Qiskit
2.5.2 in both directions: pinned fixtures and a generated set, explicit
parameter mapping, statevectors with the predicted phase only, counts and bit
order), and the from_qasm3 fuzz target in CI (import, export, re-import,
fixed point, binding). The backends' refusal of a circuit OpenQASM 2.0 cannot
express: to_py_object_rejects_a_circuit_openqasm2_cannot_express
(polypus-infrastructure), rejects_a_circuit_openqasm2_cannot_express
(QMIO), a_circuit_openqasm2_cannot_express_is_rejected_without_a_worker
(polypus-subprocess-backend), and
test_running_a_circuit_openqasm2_cannot_express_raises_instead_of_panicking
in tests/python/test_qasm3.py.
C-11 · Native QML (polypus-qml problem ↔ oracle, and polypus.qml.Model)¶
This contract governs the native form of quantum machine learning: a model that
Polypus builds, reads out and scores itself, as opposed to the Qiskit form of
C-8, whose circuits are opaque and scored by the caller's cost. The two forms
are separate entry points that share the oracle, the scheduler and the
optimizers underneath (docs/adr/0007-native-qml.md). The contract has a
Rust half — the seam between a QmlProblem and the oracle that scores it, a
Rust-to-Rust contract like C-5, the loss-free expectation Jacobian beneath
it, and the quantum kernel of an encoder — and a Python half, the
polypus.qml.Model API built on it, the qml.expval/qml.jacobian/qml.vjp
primitives and qml.kernel_matrix.
The problem ↔ oracle seam (Rust)¶
A QmlProblem bundles a compiled model, a training set and a loss, and exposes
exactly what an oracle needs: bind these parameters into circuits and here
are the results, give me the fitness (and its gradient). Backend, shots,
batching and distribution are the oracle's concern.
- (a)
bind_batchshape and order.bind_batch(θ)returns exactlynum_circuits()ConcreteCircuits in a stable sample-major order, one per training sample. Results handed back tofitness_from_counts(or its exact twinfitness_from_probabilities) must be in the same order: misaligned results are a corrupt result, so the order is specified and tested, never assumed. - (b) Finite fitness or typed error. The fitness is
−mean_loss(the optimizers maximise): a finitef64or a typedQmlError, neverNaN.BinaryCrossEntropyclamps its probability away from thelogsingularities; the unsupervisedExpectationloss is−⟨O₀⟩, so its fitness is the mean expectation; non-finite predictions are impossible upstream (the dataset and circuits reject them), and a problem never has zero samples. Results of the wrong length are a typedQmlError::CountsLengthMismatch. - (c) Emitted circuits obey C-4 and C-2. Every bound circuit ends in one
measure_all(C-4) and uses only the C-2 vocabulary, by construction: the model emits throughpolypus-circuit's builder only. - (d)
num_params()is stable and positive. Fixed atcompiletime and> 0(a model without trainable parameters isValidationError::NoTrainableParams), it is thedimensionsthe optimizer consumes under C-5. - (e) The gradient is exact.
gradient_circuits(θ)andgradient_from_counts/gradient_from_probabilitiesgive∂fitness/∂θby the parameter-shift rule, applied per occurrence: a parameter that several gates share (convolution and pooling reuse theirs across qubit pairs) is shifted at each gate in turn and the results are summed. With exact probabilities it matches a central finite difference of the fitness to near machine precision for every layer. One gradient runsnum_gradient_circuits() = num_circuits · (1 + 2 · occurrences)circuits. The rule is exact only for gatesexp(−iθP/2)withPa Pauli product; everyGateInstructionkind is classified (C-2), and a model containing one the rule cannot handle has no parameter-shift gradient (QmlError::NoExactGradient, raised lazily, so gradient-free optimizers still train it). Its message names the instruction (position and gate); for a gate only the adjoint differentiates (below) it says that the gradient with shots cannot differentiate it and exact mode (exact=True) can. - Adjoint differentiation. For a caller that holds the exact statevector,
adjoint_runs(θ, base)andgradient_from_adjointgive the same gradient with no shifted circuit: one run per sample — the untied template bound atθ, which is the circuitbind_batch(θ)gives, with every trainable gate differentiated and the loss's chain rule folded into its diagonal observable — wherebaseisθ's exact probabilities (the loss is not linear in the expectations). It differentiates the same gates per occurrence, sums a shared parameter's gates the same way, and fails with the sameNoExactGradient. It is the shift gradient to rounding, not bit for bit (the sums run in another order); the native simulator computes it in about three simulations holding two statevectors (StatevectorSimulator::adjoint_gradient), against2 · occurrences + 1circuits. - Gates only the adjoint differentiates (#561). The adjoint also takes the
controlled rotations, the phase gates and the
ufamily (C-2), which have no two-term shift rule: each angle through its generator, the phase ofcu/cu3relative to the control included,u0with derivative0. A model with one is built like any other; its occurrences are its trainable angles, numbered in gate order and, within a gate, in angle order (GateInstruction::angles:θ, φ, λ, thencu'sγ;u2'sφ, λ), andadjoint_runs/gradient_from_adjointgive its exact gradient — the derivative of the fitness, a parameter several angles share summed — while every parameter-shift method (num_gradient_circuits,gradient_circuits,gradient_from_counts,gradient_from_probabilities) fails withNoExactGradient. One that reads the sample, an expression angle, or the call of a declared gate still has no exact gradient at all, and that error comes first. No layer emits these gates today, so no model built from Python reaches either the capability or the error. - (f) The oracle. The
QmlOraclescores a native problem (QmlSource::Native) through the same candidate windows as the Qiskit form: one finite fitness per candidate (C-5), sampled through the planner or, in exact mode, fromNativeStatevectorBackend::run_circuits_exact_on_states(C-3's exact probabilities, read from each circuit's statevector, same windows). In exact mode each circuit is read as soon as it is simulated, byQmlProblem::read_state(⟨O₀⟩for a scalar loss, every readout observable for the categorical one), straight from its amplitudes throughExactState, with no map of its probabilities built (#628): fitness, the shift gradient and the adjoint runs come from those readings (fitness_from_expectations,gradient_from_expectations,adjoint_runs_from_expectations), so the exact path needs no memory beyond its statevectors (#645, #628), and the shift fallback below needs one statevector, as it says. Each reading is computed by the arithmetic the*_from_probabilitiesreaders use, on the same states in the same order, so every value is theirs bit for bit; enforced byreadings_of_the_maps_give_what_the_maps_give_bit_for_bitandstates_read_as_their_maps_do_bit_for_bitincrates/polypus-qml/src/problem.rsand the oracle's exact tests, which compare with the map readers. The exactqml.expval,qml.jacobianandqml.vjpread their circuits the same way (CompiledModel::expectations_from_state,ExpectationJacobian::jacobian_from_expectations;exact_primitives_read_expectations_that_match_the_maps_bit_for_bitincrates/polypus/src/bindings/qml.rs, and, incrates/polypus-qml/tests/jacobian.rs, every Jacobiancrate_jacobiancomputes and every block ofblocks_concatenate_to_the_whole_jacobian);TrainedModel.predict(exact=True)reads each row's decision the same way (CompiledModel::predict_from_state;exact_predictions_are_the_maps_decisions_bit_for_bit).TrainedModel.run(exact=True), which returns the probabilities, keeps the maps (run_circuits_exact), and the exact kernel builds none (fidelity_matrix). It is also the run'sGradientOracle, for Adam. Its exact gradient is the adjoint one ((e)):θ's base circuits run exactly, giving the value and the chain rule, then one adjoint run per sample onNativeStatevectorBackend::run_adjoint, which counts two statevectors per run against the memory budget. When the budget holds one statevector of the width but not two (NativeStatevectorBackend::adjoint_fits), it is the parameter shift's instead, logged atinfothe first time on that backend (once per fit, or perqml.jacobiancall, not once per gradient) — unless the model is one only the adjoint differentiates ((e)), which has no shift to fall back to: the caller asksQmlProblem::check_shift_fallback(orExpectationJacobian::check_shift_fallback) first, and the error isNoExactGradientnaming the memory of two statevectors and the instruction, before anything runs; when the budget holds none, the error is the exact path'sInsufficientMemory. The sampled (shots) gradient is always the parameter shift's. Without a minibatch itsvalue_and_gradientreturnsθ's fitness, read from the gradient's own base circuits (those that lead the shift's batch, or the exact run that precedes the adjoint), with the gradient, so an Adam iteration is one call andθ's circuits run once; in exact mode that value is, bit for bit, whatevaluate_batchreturns forθ. With a minibatch it returnsNone(those base circuits are the minibatch's, and Adam tracks its best on every sample), and Adam scoresθapart. Itsscores_thetadeclares which,trueexactly without a minibatch, so the walltime projection counts an Adam iteration as one call without a minibatch and two with one (C-5); enforced bythe_native_gradient_declares_whether_it_scores_thetaincrates/polypus-evaluation/src/qml_oracle.rsand, through the factory'sOracles,the_factory_hands_out_each_role_the_source_has. With a minibatch, one subset of the samples is drawn per call, from the run's seed and a call counter, and shared by every candidate of anevaluate_batchand by the base and every shift of a gradient;evaluate_fullscores every sample (the minibatch rules of C-5). - (g) The expectation Jacobian (loss-free).
CompiledModel::jacobian(samples, wrt)builds anExpectationJacobian: the circuits and the reader of∂⟨O_o⟩(x_s, θ)for every readout observableO_oand samplex_s, with no labels and no loss, so it takes every readout (Argmaxincluded, whichQmlProblempairs only with the categorical loss).wrtisParams(shape(samples, observables, num_params)),Inputs(shape(samples, observables, num_features)) orBoth(the two, from one set of circuits); theJacobianit reads is flat and row-major, a partwrtdid not ask forNone.CompiledModel::expectations_from_counts/expectations_from_probabilitiesread the expectations themselves, one sample at a time. - Mechanics. (e)'s, reused: every template is untied and each occurrence
shifted by
±π/2on its own. A trainable gate adds(⟨O⟩(+) − ⟨O⟩(−))/2to the parameter it reads (summed over the gates that share it). The encoders record which gates read the sample and the chain-rule factor of each feature they read: an angle encoder'sR(x_f)and an IQP encoder'sRz(x_f)have factor1; an IQPRzz(x_i·x_j)hasx_jtowardsx_iandx_itowardsx_j, and is shifted once for both. Data re-uploading sums the gates that read a feature. Recording this changes no gate: every template is, gate for gate, what it was. - Adjoint differentiation. (e)'s, for the Jacobian:
adjoint_runs(θ)on anExpectationJacobianor a block gives one run per sample and readout observable (num_adjoint_runs), sample-major, each differentiating the gates the shift would move, andjacobian_from_adjointreads them through the same bookkeeping (parameter, or feature times its chain-rule factor), with the same blocks. No loss: the observable is the readout's own. It is the shift's Jacobian to rounding, and, on a model only the adjoint differentiates ((e)), the Jacobian itself. - Vector-Jacobian product (#559).
Jacobian::vjp(v)contracts a Jacobian with a cotangentv, flat and row-major(samples, observables): aVjpwhose parts are, per samples,Σ_o v[s][o]·J[s][o][·], flat and row-major(samples, num_params)and(samples, num_features), a partwrtdid not ask forNone; values are taken as they are (NaN · 0isNaN). By adjoint differentiation,vjp_runs(θ, v)on anExpectationJacobianor a block gives one run per sample (num_vjp_runs), whatever the number of observables: the circuit and the gates ofadjoint_runs, with the diagonal observableΣ_o v[s][o]·O_o(DiagonalObservable::combine), sinceΣ_o v_o ∂⟨O_o⟩ = ∂⟨Σ_o v_o O_o⟩;vjp_from_adjointreads its derivatives through the same bookkeeping into the sameVjp. It is the shift Jacobian's contraction to rounding, and blocks concatenate row for row. A non-finite value invreaches its sample's observable as it is, and so do finite values large enough to overflow the combined weight:DiagonalObservable::weight_bound()(Σ |c|over its terms, a bound on every eigenvalue, rounding included) is then not finite, and a simulator may refuse to weigh such an observable (the native one does:polypus-simrefuses non-finite weights); the caller that wants the cotangent to reach the product as the contraction does takesadjoint_runsandJacobian::vjpfor that sample instead, on a one-sample block, so no sample's product depends on another's (the binding ofqml.vjpdoes so already past a quarter off64::MAX, below).vjp_weight_bounds(v)gives each sample's bound — theweight_boundof the observablevjp_runswould give its run, bit for bit — fromvand the readout alone, without binding a circuit, so the route can be chosen before any run is built. Avof the wrong length, like derivatives of the wrong length, isQmlError::CountsLengthMismatch. On a model only the adjoint differentiates ((e)),vjp_runsworks asadjoint_runsdoes, and the shifted circuits the exact route would fall back to when two statevectors do not fit the memory budget are refused as the Jacobian's are ((f)). - Circuits and order.
2 · shiftscircuits per sample and no unshifted one,shiftscounting the gates that read a parameter (a parameter shared byggates countsgtimes) forParams, the gates that read the sample forInputs, both forBoth; sample-major, and per sample the+π/2then the−π/2circuit of each shifted gate in gate order. Results come back in the same order; the wrong number isQmlError::CountsLengthMismatch. It can be bound and read block by block (blocks,block(range)), the blocks' Jacobians concatenating to the whole one value for value. - Exactness. From exact probabilities it is the Jacobian: it matches a
central finite difference of the expectations to near machine precision
for every layer and readout (and the inputs of angle and IQP encoders);
from counts, an unbiased estimator. The chain rule over it,
−(1/n)·Σ_i Σ_o ∂loss/∂⟨O_o⟩(x_i) · J[i, o, :], isQmlProblem's gradient for every loss. - Errors, at construction but one. A sample of the wrong width or one its
encoder rejects is that
QmlError; a model no exact gradient differentiates isQmlError::NoExactGradient, whateverwrt; withInputsorBoth, an amplitude or basis encoder, whose angles have no derivative in the sample, isQmlError::NoInputGradientnaming it; samples that read their parameters or features through different gates areQmlError::NoExactGradient, never a silently wrong Jacobian. The one error after construction: a model only the adjoint differentiates ((e)) is built, and its shifted circuits (circuits) and their readers (jacobian_from_counts,jacobian_from_probabilities) fail withNoExactGradient; its adjoint runs work.qml.jacobian(exact=True)'s memory fallback is (f)'s. - (h) The quantum kernel.
FeatureMap::compile(num_qubits, layers, num_features)compiles encoders alone (no ansatz, no readout) through the layers' ownplan(plan_layers, shared withQuantumModel::compile), so a stack raises the errors it raises in a model (AmplitudeEncoderNotFirst,TooManyFeatures,NotEnoughQubits,ConvNeedsQubits, …); a layer that reserves parameters isValidationError::TrainableLayerInFeatureMap. Itscircuit(x)isU(x): gate for gate what a model's template emits for those layers, unmeasured, and a sample they reject is thatQmlError. AFidelityKernelover the states ofx(rows) andy(columns, orxagain for the symmetric kernel) numbers its pairs row-major — every(i, j), or onlyj >= i, diagonal included,n(n+1)/2of them — and gives, per pair, the compute-uncompute circuitU(x_i), thenU(y_j)†(ConcreteCircuit::inverse, C-2, built for every column once, by the first request for a pair's circuit, never by a caller that only takes the states), then onemeasure_all(C-4, C-2 by construction), and reads its counts ascounts["0"·n] / Σ counts(nthe encoder's qubits, C-3; an absent key is0, an empty or zero totalQmlError::EmptyCounts, a key of another widthQmlError::CountsWidthMismatch, neverNaN), or its exact probabilities asP(0…0)clamped to[0, 1].matrix(values)assembles one value per pair into therows × columnsmatrix, a symmetric kernel's lower half the mirror of its upper one, bit for bit;place(matrix, first, values)writes a block of pairs into azero_matrix()the same way, so blocks of any size give that matrix bit for bit and a caller never holds the values beside it. A matrix whose entries are not addressable isQmlError::KernelTooLarge:FidelityKernel::newchecks it before it encodes any sample,from_stateswhen it is built, over states already encoded (the orderqml.kernel_matrixkeeps, every check ofx1before those ofx2); states of different widths areQmlError::StateWidthMismatch. The circuits can be taken in blocks (circuits(range)), and the states themselves (row_states,column_states) serve a caller that takes inner products instead:NativeStatevectorBackend::fidelity_matrixgives|⟨a_i|b_j⟩|²and picks its route itself, by the memory budget with the result counted: itsrows × columns × 8bytes come off the budget before the statevectors are sized. With room for two statevectors beside it, from the statevectors, each simulated once when they all fit (in tiles otherwise), each entry one inner product summed sequentially in basis-state order, so the matrix is the samef64s for every such budget, tile and thread count, and the compute-uncompute probabilities to rounding. With room for one but not two, each entry is theP(0…0)ofU(x_i)thenU(y_j)†on one statevector, one entry at a time, logged atinfoonce per backend: the inner products' values to rounding, with no result map kept per circuit. A known budget (never the blind fallback, which takes the inner products) that leaves no room for one statevector beside the matrix isInsufficientMemoryForResult(aBackendErrorvariant) naming the matrix, the statevector and the budget, and one that does not hold one statevector at all isInsufficientMemory, the exact path's own refusal, both before anything is allocated or simulated. The circuits it takes are thoseConcreteCircuit::inverseinverts, whatever the route: one that measures (measure,measure_all) or calls a declared gate, or states of different widths, areUnsupportedCircuit;should_cancelstops it withAbortedon either route.
The Python API (polypus.qml)¶
Building a model. Model(encoder, ansatz, readout) joins an Encoder (the
layers that load each sample), an Ansatz (the trainable layers, which may also
re-upload the data) and a Readout. It copies the three, so building on them
afterwards does not change it, and it holds no trained parameters. Everything
that does not depend on the data is checked where it is written, as a plain
ValueError, as polypus.Circuit's builders raise (the checks of fit,
predict and run below are polypus.ConfigurationError):
- each
Encoder/Ansatzbuilder call re-checks its layers (a misplaced amplitude encoder, pooling below two active qubits, a convolution whosepairingselects no pair ("odd_pairs"below three active qubits,"even_pairs"and"alternating"below two;ValidationError::ConvNeedsQubits), astrongly_entanglingrange out of bounds) and leaves the object as it was when it raises; Modelchecks that theEncoderand theAnsatzhave the same width, that some layer loads the data, that the layers reserve trainable parameters, and that the readout's positions exist among the qubits still active at the end;- a count argument that is negative or larger than a
usizeholds is refused at the call, before the layer is checked:reps, thenum_qubitsofEncoder/Ansatz(where0is refused too, with its own message), and a Pauli position, inZ/X/Yand in the[(pauli, position), …]list (below). A model has at mostMAX_MODEL_QUBITS(1 000 000) qubits:Encoder/Ansatzrefuse more at construction, andcompile(soqml.loadand the kernel'sFeatureMap) withValidationError::TooManyQubits. The gates a model's layers emit are counted in each layer'splan, before any gate or parameter of it exists, againstMAX_MODEL_GATES(4 000 000): a layer that takes the model past it isValidationError::ModelTooLargewithSizeLimit::Budget, and one whose count does not fit in ausize(a hugereps) the same variant withSizeLimit::Overflow; the two messages differ. Encoders are counted for the feature countcompileis given: none at the builder; the samples' wherever the model meets data, where the error is that call's own (apolypus.ConfigurationErrorinfit,predict,run,qml.expval/jacobian/vjpandqml.kernel_matrix, aValueErrorincircuit(x)). The basis encoder is counted as if every feature were1.0; the readout's basis change and measurements are not counted. An amplitude encoder emits2^(n+1) − 3gates, so it takes at most 20 qubits. All of these are aValueErrorthat leaves the object as it was, never PyO3'sOverflowErroror a panic. A count of another type (abool, NumPy'sbool_included, astr, afloat) is aTypeError; an object with__index__(a NumPy integer) is the integer it returns, which an out-of-range message shows.simplified_two_design(reps)takes onlyreps: it reservesn + 2·(n − 1)·repsparameters for thenqubits active where it sits (oneRyper qubit, then two per pair per block), has no string options and so no row in the Options table below, and with one active qubit (no pairs) is that singleRylayer for anyreps.
What depends on the data — how many features the encoders can carry — is
checked when the model meets a dataset. num_params and num_observables (the
readout's observables, the columns of qml.expval) are fixed at construction.
A Model pickles, and so copies with copy.deepcopy, as the JSON of its spec
(the spec of the save format below), rebuilt by Model._from_spec through
the checks qml.load runs: a corrupt or edited spec is a ValueError, never an
inconsistent model.
Readout observables. Readout(observables, decision="raw", threshold=None).
Each observable is a polypus.qml.PauliTerm (Z(0), Z(0) @ Z(1): one product,
coefficient 1.0), a polypus.qml.Observable (a weighted sum
Observable([(0.5, Z(0)), (1.5, Z(0) @ Z(1))]), the only form with coefficients
or several terms) or a [(pauli, position), …] list, the literal spelling of a
PauliTerm. They are told apart by type, never by the shape of the tuples, and
may be mixed. Positions are logical: they index the qubits still active after
any pooling. A non-finite coefficient, an unknown Pauli or a position repeated
in one product is a ValueError (Z(0) @ Z(0) raises at the @), and so is
a negative or oversized position, Z(-1) or [("z", -1)] (in the list form
the message names the term or observable and the factor); anything else is a
TypeError naming the three forms. A list is read factor by factor, and the
first malformed factor or out-of-range position decides which of the two it
is; an unknown Pauli or a repeated position is checked once every factor has
been read. "argmax" reads one observable per class (at least two); the
other decisions predict from the first.
threshold is required by "threshold" and rejected by every other decision.
Measurement basis (single group). A readout may measure X/Y: the model
inserts the basis change (H for X; Sdg then H for Y) before the
terminal measurement, provided the whole readout resolves to one basis group
(every term agrees on the Pauli of each qubit it touches). Conflicting bases
inside one observable are ValidationError::ObservableHasIncompatibleBases; a
readout needing more than one group is
ValidationError::ReadoutNeedsMultipleBasisGroups: rejected, never mismeasured.
Options. Every option in the table below is a string from a closed set,
checked when it is given; any other value is a ValueError listing the valid
ones. The typing stubs spell each set as a Literal.
| Option | Accepted values |
|---|---|
angle_encoder(axis=), hardware_efficient(rotations=[…]) |
"rx", "ry", "rz" |
hardware_efficient(entanglement=), iqp_encoder(entanglement=) |
"linear", "circular", "full" |
hardware_efficient(entangler=), strongly_entangling(entangler=) |
"cx", "cz" |
conv(block=) |
"basic", "cartan" |
conv(pairing=) |
"even_pairs", "odd_pairs", "alternating" |
pool(block=) |
"basic" |
pool(keep=) |
"even_positions", "odd_positions" |
Readout(decision=) |
"raw", "sign", "threshold", "argmax" |
fit(loss=) |
"squared_error", "binary_cross_entropy", "hinge", "categorical_cross_entropy", "expectation" |
qml.jacobian(wrt=), qml.vjp(wrt=) |
"params", "inputs", "both" (a polypus.ConfigurationError, like every check of the primitives) |
The one option that is not a string is strongly_entangling(ranges=): None
(PennyLane's default, r = (layer mod (n − 1)) + 1) or one integer per layer,
each in 1..=n−1 for the n qubits active where the layer sits (after any
pooling). A count other than reps, or a range outside those bounds, is
ValidationError::StronglyEntanglingRangesLength /
StronglyEntanglingRangeOutOfBounds, a ValueError at the call; with one
active qubit no entangler is emitted, so only the count is checked. A range
is a count argument like reps: a negative one, or one larger than a usize
holds, is the same ValueError at the call.
Execution integers. shots, n_qpus, nodes and cores_per_qpu
(unsigned 32-bit integers) and seed (unsigned 64-bit) of Model.fit,
TrainedModel.predict/run, qml.expval, qml.jacobian, qml.vjp and
qml.kernel_matrix follow the rule of the counts, at the entry point:
- a negative one, or one larger than its type holds (4294967295;
18446744073709551615 for
seed), is apolypus.ConfigurationErrornaming the argument and the value (shots must be at most 4294967295, got 4294967296), raised before a backend exists, never PyO3'sOverflowError. A negativeshotsorn_qpushas the message of0(shots must be >= 1, got -1), and so does a negativenodesorcores_per_qpuoncunqa(nodes must be >= 1 for the 'cunqa' infrastructure, got -1); elsewhere it isnodes must be an integer >= 0, got -1. A negativeseedisseed must be an integer >= 0 or None, got -1,polypus.torch's words.nodesandcores_per_qpuare refused on every infrastructure, although0is refused oncunqaonly; - a
bool(Trueis not one shot), NumPy'sbool_included, or another type (afloatsuch as16.0, astr,Noneexcept forseed) is aTypeError, raised as the arguments are read, before any check of the call; an object with__index__(a NumPy integer) is the integer it returns, which an out-of-range message shows; - each range is checked at its place in the order of the checks, one
argument after the other:
shots's range then its>= 1, thenn_qpus's range then its>= 1;nodes's range then, oncunqa, its>= 1, then the same forcores_per_qpu, thenwalltime(oncunqa);seedright before aseedonqmiois refused, and infit, which has no such refusal, afteridandloss, before the optimizer seed is resolved (C-7). The narrower range of Aer and CUNQA (below2**63, C-7 Seed range) is checked later, once the backend's configuration is built.
Dataset.train_test_split(seed=…) follows the same rule as a builder: an
out-of-range seed is a plain ValueError with the same message, a bool a
TypeError, a NumPy integer the integer it holds.
Training (Model.fit). fit(x, y=None, *, method, loss=None, …); every
argument after y is keyword-only and method is required. It returns a
TrainResult (C-7) whose best_params has num_params values. All the checks
below run before a backend exists and raise polypus.ConfigurationError, which
is also a ValueError (#418), as train's do:
- Data.
xis rows of features or apolypus.qml.Dataset; with aDataset,yis an error (it carries its own labels, or none). Labels fromyfollow C-8's checks, their messages namingy; the rows must be non-empty, each with at least one feature (a zero-width row would encode nothing and predict a constant, #513), of equal width and finite. Fewer features than qubits stays accepted. Every value ofxis a real number (abool, Python's or NumPy's, reads as 0 or 1, unlike an execution integer or a count, where it is aTypeError, above): a complex one, Python's or NumPy's, in any container (a list, a NumPy array of complex dtype, an object array, a 0-d array in a list, or a 0-d object array holding one), is aTypeErrornaming its 0-based row and column, whatever its imaginary part, rather than losing its imaginary part (#602). The same holds for every native reader of rows (predict,run,qml.Dataset, the primitives,qml.kernel_matrix) and, naming the index, for the labels ofyand ofqml.Dataset(x, y). - Labels and loss. With labels,
lossis required and is a supervised loss;"expectation"(which ignores labels) is an error. Without labels (y=None, or aDatasetbuilt without them),loss=Nonemeans"expectation"and a supervised loss is an error: labels are never ignored, and a supervised loss never trains against made-up labels."argmax"pairs with"categorical_cross_entropy"only, and every other decision with a scalar loss. Label domains are the loss's (±1 for"hinge", 0/1 for"binary_cross_entropy", class indices below the number of observables for"categorical_cross_entropy"). exact=Truereplaces sampling with exact probabilities (soshotsdoes not matter) and needsinfrastructure="local"withbackend="polypus".batch_sizemust satisfy1 <= batch_size < number of samples; the reportedbest_fitnessis on every sample (C-5). A negative integer, or one larger than ausizeholds, is refused with the same message, never PyO3'sOverflowError; abatch_sizethat is not an integer (aboolincluded) is aTypeError.initial_point(keyword-only, defaultNone) is C-5's starting point, withnum_paramsasdimensions: its checks, after the optimizer's configuration (checked with or without a point), aretrain's, with its messages, and a list, tuple or NumPy array is accepted, such as theparamsof aTrainedModelread back withqml.load, to train it on.final_shots(keyword-only, defaultNone) is C-5's final re-evaluation, withtrain's checks; its batch scores every sample, with or withoutbatch_size, intofinal_paramsandfinal_fitness. Withexact=True, which uses no shots, any validfinal_shotsis an error; a malformed one fails its own check first, andexact=Trueoff the local native simulator failsexact's.polypus.Rotosolveneeds what its closed-form step assumes (C-5):loss="expectation", the one loss linear in the measured distribution (another is an error naming it), and every trainable parameter the angle of exactly one rotation, checked withParameterizedCircuit::check_single_frequencyon the model's template (an error with the first problem; aconvorpoollayer over more than one pair fails it, since it shares each parameter across the pairs). Every other optimizer takes any model.callbackisNoneor a callable, as forpolypus.train(C-5); one that is neither is aTypeError, not aConfigurationError, raised right after thefinal_shotscheck, before a backend exists. A stop it asks for still sends thefinal_shotsbatch. Itsevaluationscount Adam's θ, which the exact parameter-shift gradient measures in its own batch, but not the shifted circuits; withbatch_sizeitsbest_fitnessis a minibatch estimate except for Adam.backend=Noneis"polypus"(the native simulator) oninfrastructure="local"and"aer"elsewhere (CUNQA's QPUs run Aer; a registry backend such as QMIO does not read it); an explicitbackendwins. The other execution arguments followpolypus.train(C-1, C-7, C-9), and their integers the Execution integers rule above.
Inference. model.bind(params) checks that params has exactly
num_params finite values (ValueError otherwise) and returns an immutable
TrainedModel; the Model is unchanged. TrainedModel.predict(x, *, …)
returns one decision per row: an int for "sign" and "threshold" (±1) and
for "argmax" (the class index), a float for "raw" (the expectation).
TrainedModel.run(x, *, …) returns the raw results: a RunResult whose
counts holds one C-3 dict per row (merged_counts is None), or with
exact=True an ExactResult whose probabilities holds one dict per row,
keyed like the counts. Both take rows or a Dataset (its labels are not used);
exact and backend=None follow fit's rules, and so do their checks (the
execution integers, the rows against the model, exact, a seed on qmio):
before a backend exists, as polypus.ConfigurationError, in this order:
shots and n_qpus, nodes, cores_per_qpu and the CUNQA allocation,
exact, the rows against the model, the range of seed, a seed on
qmio, a seed of 2**63 or more on Aer or CUNQA (C-7).
Inspecting the circuit. model.circuit(x, params=None) and
TrainedModel.circuit(x) return the polypus.Circuit the model runs for the
one sample x (a flat sequence of floats or a 1-D NumPy array): the features
fixed, the trainable layers, the readout's basis change and the terminal
measure_all. It is the model's only circuit, since the readout resolves to a
single basis group. Without params the trainable angles stay free:
num_params equals the model's and param_names are theta_0, theta_1, …,
in the order of best_params. With params (checked as bind checks them) it
is model.bind(params).circuit(x), every angle fixed and num_params == 0.
The bound circuit is the one run and predict execute for that row: run on
the native simulator with the same seed and shots it gives run([x])'s counts,
and its statevector gives run([x], exact=True)'s probabilities. x is
checked as a row of fit: a feature count the encoders cannot carry, a
non-finite value or, for the amplitude encoder, a zero sample is a
ValueError; several rows or a Dataset is a TypeError, and so is a
complex value, naming its 0-based position in x as a row's does (not the
TypeError for what is not one sample). These are plain
ValueErrors, as bind raises, not polypus.ConfigurationError: circuit
builds a circuit and runs nothing, so the same row that run rejects with a
ConfigurationError is a ValueError here. The model is unchanged, and each
call returns a new Circuit.
Expectation and Jacobian primitives. qml.expval(model, x, params, *, …),
qml.jacobian(model, x, params, *, wrt="params", …) and
qml.vjp(model, x, params, cotangent, *, wrt="params", …) expose (g) to
Python, for a training loop of the caller's own:
- Arguments.
modelis apolypus.qml.Model(anything else, aTrainedModelincluded, is aTypeError);xis rows or aDataset(its labels are not used);paramsis a list, tuple or NumPy array of exactlynum_paramsfinite values, checked asbindchecks them. The execution arguments areTrainedModel.run's, keyword-only, with its rules:exactneedsinfrastructure="local"andbackend="polypus",backend=Nonegoes by infrastructure,seedis drawn when omitted and refused onqmio(C-7).vjp'scotangent,v, is rows as lists or tuples, or a NumPy array, of shape exactly(rows, observables), the rows ofxand the model's observables. Its values are read asx's are, each a real number (aboolincluded; a real or boolean NumPy dtype is converted tofloat64), so a string,None, another object or a complex value (a complex dtype, or a complex number in an object array) is theTypeErrorxraises for it, rather than losing its imaginary part; aNaNor an infinity is taken as it is, not refused. - Results.
float64numpy.ndarrays, C-contiguous, rows in row order:expval→(rows, observables)with every readout observable, whatever the decision (one column per class for"argmax", the weighted sum for anObservable);jacobian→(rows, observables, num_params)forwrt="params",(rows, observables, features)for"inputs", and the tuple of both for"both", each identical to its separate call;vjp→ the vector-Jacobian product,Σ_r,o v[r,o]·J_θ[r,o,:]of shape(num_params,)(summed over the rows) for"params",Σ_o v[r,o]·J_x[r,o,:]of shape(rows, features)for"inputs", and the tuple of both for"both", each identical to its separate call. A non-finite value invpropagates as it does through the contraction ofjacobian's result (NaN · 0isNaN). Withexact=Truethey are the exact values, whatrun(exact=True)andpredict(exact=True)read; with shots, unbiased estimates. No manifest: the seed andidare logged; pass aseedto replay. - The input Jacobian covers angle encoders, angle re-uploading and IQP
encoders (re-uploaded or not), through (g)'s chain rule (
Rz(x_i)factor1,Rzz(x_i·x_j)factorsx_jandx_i). An amplitude or basis encoder, in theEncoderor theAnsatz, has no derivative in the sample:wrt="inputs"or"both"with one is apolypus.ConfigurationErrornaming it;"params"takes any model. - Circuits.
expvalruns one per row;jacobian2 · shiftsper row ((g): every gate that reads a parameter, once per gate, every encoder gate that reads the row, an IQPRzzonce for its two features), and no unshifted circuit. Withexact=Trueit is (g)'s adjoint differentiation instead, one run per row and observable onNativeStatevectorBackend::run_adjoint, unless the memory budget holds one statevector of the width but not two: then the shifted circuits, logged atinfo(as (f)). The result is the same to rounding either way.vjprunsjacobian's circuits and contracts each block's Jacobian with the block's rows ofv, so with shots and the sameseedit is the contraction ofjacobian's result, to rounding; withexact=Trueit takes (g)'s vector-Jacobian product instead, one adjoint run per row whatever the number of observables, with the same fallback to the shifted circuits. A row whose combined observable cannot be weighed safely — a non-finite value in its row ofv, or aweight_boundpastf64::MAX / 4, so that the simulator never sees a weight it refuses (its sweep and each derivative stay within the bound; the factor 4 is room for a few sums over the gates that share a parameter and chain-rule factors, not a guarantee against an overflow of the product nearf64::MAX) — takesjacobian's runs, one per observable, and contracts them, so its result is still the contraction. The route is decided per row, never per block, so a row's product does not depend on the others' nor on the blocks. - Execution. One backend and one scheduler per call — one connection, one
qraiseon CUNQA — closed on every way out, errors and Ctrl+C included. The rows run in sequential blocks, each bound, run and dropped before the next (the planner splits a block into waves), so the live circuits stay bounded. Rows per block are theQmlOracle's candidate window, sized by the same function (polypus_evaluation::candidate_window_size, with rows for candidates): derived from the host's cores, the backend's concurrency and the circuits per row, never configured. The whole block loop runs with the GIL released, and Ctrl+C raisesKeyboardInterruptbetween blocks (the exact path included, which has no planner) and between waves, and, during an exact block's adjoint runs, inside the block: the calling thread, the one a Ctrl+C can be seen on, polls the run's interrupt guard while they run on rayon's threads and stops them, with the sameKeyboardInterrupt. The result does not depend on the blocks: rows come back in row order, and a call on some rows equals the concatenation of calls on chunks of them (forvjp's"params", which sums over the rows, their sum, to rounding: the rows are summed in row order whatever the blocks). - Checks. Every one runs before a backend exists and raises
polypus.ConfigurationError, theTypeErrors ofx's and the cotangent's values excepted (below), in order:wrt;shots, thenn_qpus(each its range, then>= 1),nodes, thencores_per_qpu(each its range, on every infrastructure, then its part of the CUNQA allocation), the rest of the CUNQA allocation andexact; the rows (each value read as a real number, a complex onex'sTypeError), then the rows against the model;params; forvjp, thecotangent(its rows not ragged; a complex dtype,x'sTypeError; then its shape, the error naming the expected and the received one; then each value read as a number, aTypeErroras forx); the model and rows againstwrt((g)'s errors); the range ofseed, then aseedonqmio, then aseedof2**63or more on Aer or CUNQA (C-7). TheTypeErrorformodelcomes first, and before it, as the arguments are read, that of an execution integer that is not an integer (aboolincluded). Only NumPy'sValueErrorbecomes the cotangent'sConfigurationError; any other exception of NumPy's (aMemoryError) propagates as it is.
Quantum kernels. qml.kernel_matrix(encoder, x1, x2=None, *, shots=1024,
infrastructure="local", n_qpus=1, nodes=1, cores_per_qpu=2, walltime=None,
options=None, sim_method="automatic", noise_model=None, backend=None,
seed=None, exact=False) exposes (h) to Python:
- Result.
K[i, j] = |⟨φ(x1_i)|φ(x2_j)⟩|²,|φ(x)⟩ = U(x)|0…0⟩for theEncoder's layers, as afloat64numpy.ndarray, C-contiguous, of shape(len(x1), len(x2))—(len(x1), len(x1))withoutx2— with every entry in[0, 1]. No manifest: the seed andidare logged. - Arguments.
encoderis apolypus.qml.Encoder; anything else (anAnsatz, aModel, aTrainedModel, aCircuit) is aTypeErrornaming what it takes (trainable kernels are not supported).x1andx2are rows orDatasets (labels are not used). The execution arguments areqml.expval's, with its rules:exactneedsinfrastructure="local"andbackend="polypus",backend=Nonegoes by infrastructure,seedis drawn when omitted and refused onqmio(C-7). - Symmetry and diagonal. Without
x2, theN(N+1)/2pairs of the upper triangle, diagonal included, run, and the lower triangle is their mirror, soK == K.Tbit for bit. The diagonal is executed like any entry, never set to1: it is1to rounding exactly, and below it under noise. Withx2, allN·Mentries run, even for anx2equal tox1(no symmetry is detected). - Exact and shots. With
exact=True, one call tofidelity_matrix((h)), which counts the matrix itself against the memory budget and picks the route by what itslen(x1) × len(x2) × 8bytes leave: the inner products with room for two statevectors of the encoder's width, one compute-uncompute circuit per entry on one statevector with room for one (logged atinfo; the two are the same to rounding), and with no room for one the call raisespolypus.InsufficientMemoryError(apolypus.BackendError, the class a statevector that does not fit raises, C-1) naming the matrix and the budget, before anything runs; a call on fewer rows ofx1gives those rows of the whole matrix, bit for bit while both take the inner products. The exact Gram matrix is positive semi-definite to rounding. With shots, each entry is the0…0frequency of one compute-uncompute circuit, an unbiased estimator ofK; the matrix may not be positive semi-definite, and it is returned as measured, never projected. - Execution. One backend and one scheduler per call — one connection, one
qraiseon CUNQA — closed on every way out, errors and Ctrl+C included. The pairs run in sequential blocks sized likeqml.expval's rows (candidate_window_size, one circuit per pair), with the GIL released for the whole loop; Ctrl+C raisesKeyboardInterruptbetween blocks and waves. The exact kernel is one call that bounds its own memory (no blocks), on either of its routes, watched from the calling thread like an exactqml.jacobianblock, so Ctrl+C stops it in flight with the sameKeyboardInterrupt. With shots and a seed, the result does not depend on the blocks (every circuit's seed is its position in the call); exactly, a call on some rows ofx1equals those rows of the call on all of them, bit for bit while both take the inner products (not with shots, whose seeds follow the pairs' global positions). With shots, each block's values are written into the matrix as they are read, so the pairs' values are never held beside it. - Checks. The
TypeErrorfor an execution integer that is not an integer (aboolincluded) comes first, as the arguments are read, then theTypeErrorforencoder. Then each of these is apolypus.ConfigurationErrorraised before a backend exists, in order:shots, thenn_qpus(each its range, then>= 1),nodes, thencores_per_qpu(each its range, on every infrastructure, then its part of the CUNQA allocation), the rest of the CUNQA allocation andexact; the rows ofx1(a complex value, read before the other checks of the rows, isx'sTypeErrornamingx1and its position; then empty, zero-width, ragged, non-finite), anEncoderwith no layers, the feature count against the encoder and every sample the encoders reject (a zero sample for amplitude encoding, a non-binary one for basis encoding); the same forx2, whose rows must be as wide asx1's; a matrix too large; the range ofseed, then aseedonqmio, then aseedof2**63or more on Aer or CUNQA (C-7). The messages namex1orx2.
The PyTorch layer (polypus.torch). polypus.torch.QuantumLayer(model, *,
initial_params=None, <qml.expval's execution arguments>) is a
torch.nn.Module over a native Model, and polypus.torch.from_trained(trained,
**same) is QuantumLayer(trained.model, initial_params=trained.params, ...).
It adds no quantum logic: everything it computes comes from the primitives
above.
- Import. PyTorch is an optional extra (
polypus-quantum[torch], floor = the CPU torch CI tests).import polypusimports neitherpolypus.torchnortorch;import polypus.torchwithout PyTorch is anImportErrornaming the extra. - Arguments.
modelis aModel(aTrainedModelis aTypeErrornamingfrom_trained, which in turn takes only aTrainedModel, aModelbeing aTypeErrornamingQuantumLayer).initial_paramsis checked asbindchecks it; without it the parameters are uniform on[-π, π)from PyTorch's global generator.seedisNoneor an integer>= 0(TypeError/polypus.ConfigurationErrorat construction). The other arguments areqml.expval's, names, defaults and rules, kept and checked by it at the first forward pass, before a backend exists. The one trainable parameter isparams, 1-D,num_paramsvalues,float64unless the layer is converted (layer.float());num_paramsandnum_observablesare the model's. - Forward =
expval. A(batch, features)tensor gives(batch, num_observables); a 1-D tensor is one sample and gives(num_observables,), the row of the 2-D result; another rank is aValueError. Oneqml.expvalcall per forward pass with the whole batch; in exact mode the output is, bit for bit,qml.expval(model, x, params, exact=True). The rows' checks (empty batch, feature count, non-finite values) areexpval's errors. - Backward =
qml.vjp. Oneqml.vjpcall per backward pass (neverqml.jacobian), with the incoming gradientgas its cotangent andwrtexactly what needs a gradient ("params","inputs", or"both"), none when nothing does;∂L/∂θ = Σ_b,o g[b,o]·J_θ[b,o,:]and∂L/∂x[b] = Σ_o g[b,o]·J_x[b,o,:], so in exact mode one adjoint run per row whatever the number of observables (#559). An amplitude or basis encoder raisesvjp'spolypus.ConfigurationErroronly when the input's gradient is wanted. The backward pass is not differentiable (no second derivatives); in exact modetorch.autograd.gradcheckpasses with its default tolerances. - dtype and device. The computation is
float64on the CPU: the input and parameter are converted at the boundary; the output comes back in the input's dtype (float64for a non-floating input) and device, each gradient in its tensor's dtype and device. A complex input is aTypeError, after the one for an input that is not a tensor and before the shape'sValueError, and beforeqml.expvalis called (#602). - Seeds (C-7). With
seed=s, forward passn(counted per layer from 0, not in thestate_dict, so not thread-safe) callsexpvalwithSeedSequence([s, n, 0]).generate_state(1, uint64)[0] & (2**63 - 1)(below the Aer seed range's limit, #393) and its backward pass callsvjpwith[s, n, 1]masked the same way (a forward pass counts even when it raises, so twin layers stay in step): two layers with the sameseedreplay the same values and gradients step by step, every call has its own stream, and neighbouring seeds share none. Withoutseed,Nonereaches every call, which draws its own. Aseedonqmioisexpval'sConfigurationErrorat the first forward pass. - Cost. One backend per forward pass and one per backward pass (two
allocations per training step on CUNQA). Not supported:
torch.compile,torch.vmap.copy.deepcopyandstate_dictkeepparamsbit for bit.
Save format. TrainedModel.save(path) writes, and polypus.qml.load(path)
reads, a JSON file shared with the polypus-qml crate's TrainedModel:
{"format": "polypus.qml.TrainedModel", "version": 1, "spec": {…}, "params": […]}
- Loading checks the format and the version, then rebuilds the model through the
same checks as
Modelandbind, so a corrupt or edited file is aValueErrorand never an inconsistent model (an editedstrongly_entanglingrange included). Loading only parses JSON: it never runs code. - A new layer is a new variant of the
spec's layer list, which leaves every existing file valid, so it keepsversion1 (StronglyEntanglingandSimplifiedTwoDesignwere added this way). The reverse does not hold: an older Polypus rejects, as aValueError, a file that uses a layer it does not know. - Every parameter reads back bit for bit (the file is written with
serde_json's round-trip float formatting), so a loaded model predicts exactly as the saved one. savereplaces any file atpath, writing beside it and renaming over it, so a failure never leaves a partial file. A disk failure is anOSError(FileNotFoundError,PermissionErrorwhere they apply) naming the path.
qml.train and qml.predict take Qiskit circuits only: an Encoder or
Ansatz given to them is a TypeError before anything runs (C-8).
Enforcing test:
- Rust:
crates/polypus-qml/tests/contracts.rs: (a)–(d), and the readout and zero-sample guards;crates/polypus-qml/tests/gradient_exactness.rsandevery_instruction_kind_is_classifiedinsrc/problem.rs: (e);crates/polypus-qml/tests/adjoint.rsandthe_adjoint_gradient_needs_an_exact_gradient_tooinsrc/problem.rs, withcrates/polypus-sim/tests/adjoint.rsfor the simulator's derivative: (e)'s adjoint differentiation;- the
untie_*tests (among themuntie_numbers_every_angle_of_each_adjoint_only_gate_in_angle_order, which pins each gate's angle order) anda_model_only_the_adjoint_differentiates_gets_its_exact_gradient_from_itinsrc/problem.rs,adjoint_only_messages_name_the_gate_and_the_way_outinsrc/error.rs, and incrates/polypus-simthe adjoint-only tests oftests/adjoint.rswithevery_generator_is_the_derivative_of_the_simulated_matrixinsrc/adjoint.rs: (e)'s gates only the adjoint differentiates; crates/polypus-qml/tests/kernel.rs(every encoder against its closed form, the two exact routes, the diagonal, symmetry and the gates of a model's encoders) and the tests insrc/kernel.rs(pairs, circuits, readers, assembly, the layer checks, the size and width errors), with thefidelit*tests incrates/polypus-infrastructure/src/native.rs(the naive inner products, the tiling, the memory refusal and its fallback, rejections, cancellation) andConcreteCircuit::inverse's (C-2): (h);crates/polypus-qml/tests/jacobian.rs(withJacobian::vjp: the contraction, a zero and a non-finite cotangent, the wrong length) and the vector-Jacobian product tests oftests/adjoint.rs(one run per sample whatever the observables, the contraction of the shift Jacobian for every readout and model shape, the inputs of angle and IQP encoders, blocks, aNaNreaching only its sample,vjp_weight_boundsgiving each sample's bound bit for bit without binding) withthe_weight_bound_bounds_every_eigenvalue_and_flags_an_overflowinsrc/adjoint.rs, theuntie_traced_*tests insrc/problem.rs, the tests insrc/jacobian.rs(a structure other than sample 0's, an angle gate only the adjoint differentiates, a declared gate, an opaque encoder againstwrt), and the trace tests insrc/model.rsand the encoders: (g);- the
serde_testsandtrained_model_testsinsrc/model.rs: the save format, exact round-trip and revalidation on load; - the
native_*,a_minibatch_*,evaluate_full_*andthe_factory_*tests incrates/polypus-evaluation/src/qml_oracle.rs, theexact_*andadjoint_*tests andthe_adjoint_needs_two_statevectors_and_falls_back_to_the_shift_with_oneincrates/polypus-infrastructure/src/native.rs,the_shift_fallback_*,a_model_only_the_adjoint_differentiates_explains_each_failureanda_cancelled_exact_gradient_*inqml_oracle.rs, and theadam_*anda_minibatched_*tests incrates/polypus-orchestration/src/dispatch.rs: (f); a_bound_circuit_converts_gate_for_gateandan_invalid_concrete_circuit_is_an_error_not_a_panicincrates/polypus/src/bindings/qml.rs: the bound circuitcircuitreturns is, gate for gate, the one the model binds;final_shots_is_refused_only_with_exactthere:fit'sfinal_shotswithexact=True; and the primitive tests there (the seeded result independent of the block size, row order, one backend created and closed once, a cancellation or an error between blocks, a backend closed when no scheduler can be built over it, the array conversion, the exact Jacobian by the adjoint whatever the blocks, the exact Jacobian of a model only the adjoint differentiates that cannot fall back, a Ctrl+C inside an exact block and the watcher that stops it; forqml.vjp, one adjoint run per row whatever the observables andqml.jacobian's contraction whatever the blocks, the shift and sampled routes, a non-finite cotangent, or a finite one that overflows the weight, through the Jacobian's runs for that row only, the route decided per row so the block size changes nothing bit for bit, a row of derivatives too many or too few refused as a bookkeeping error, the exact product of a model only the adjoint differentiates that cannot fall back, a cancellation between blocks and a Ctrl+C inside one), and their kernel twins (a_seeded_kernel_*,the_exact_kernel_*,exact_rows_in_chunks_*,a_kernel_*,a_ctrl_c_stops_an_exact_kernel_in_flight), with the window tests incrates/polypus-evaluation/src/qml_oracle.rs(a_backend_*,the_lift_*,many_circuits_per_item_*,the_window_is_never_zero):qml.expval/qml.jacobian/qml.vjp/qml.kernel_matrix's execution.- Python:
tests/python/test_qml_native.py(construction, the option sets, every construction check,Datasetsplits and scaling, theqml.train/qml.predictrejection),test_qml_native_layers.py(what each layer and observable computes, against closed forms and bit-for-bit equivalences, and predictions against the results they read),test_qml_native_training.py(fit: supervised, unsupervised, exact, sampled, minibatches, seeds, every layer trained, the convergence curve, every rejection, Rotosolve's checks before the CUNQA seam and a Rotosolve climb),test_qml_native_inference.py(bind,predict,run,ExactResult, decision types, save/load and tampered files),test_qml_native_circuit.py(Model.circuitandTrainedModel.circuit: the shape and parameter names, the basis change, the drawings, counts and exact probabilities identical torun's, every rejection),test_qml_native_expval_jacobian.py(qml.expvalandqml.jacobian: types, shapes and contiguity,expvalagainstrun/predict, the Jacobian against finite differences for every layer and readout and against the chain rule of a loss, chunks, seeds, shots, every rejection),test_qml_native_vjp.py(qml.vjp: types, shapes and contiguity, the cotangent's containers, the contraction ofqml.jacobianfor every layer, readout and input encoder, exact and with the same seed, chunks, one observable, a zero, a non-finite, an overflowing, a complex and a wrongly shaped cotangent, a row that cannot be combined leaving the others bit for bit, the cotangent taking exactly the valuesxtakes, NumPy's other errors propagating, every rejection),test_qml_native_complex.py(a complex value refused with aTypeErrornaming its position, and noComplexWarning, by every native reader ofx,x1/x2andy, in every container, whatever its imaginary part;xread before the cotangent; aboolstill 0 or 1; the other rejections ofxunchanged),test_qml_native_kernel.py(qml.kernel_matrix: types, shape and contiguity, every encoder against a NumPy closed form and Qiskit's own statevectors, symmetry bit for bit, the executed diagonal, PSD, the circuits counted at the CUNQA seam, shots against exact and unbiased, seeds, chunks, every rejection and their order),test_torch_quantum_layer.py(the PyTorch layer: forward bit for bitexpvalin one call per batch,gradcheckwith default tolerances for the parameters and the inputs, the backward pass the same by the adjoint and by the shift fallback, oneqml.vjpcall per backward pass with thewrtit asks for and the incoming gradient, neverqml.jacobian, amplitude and basis encoders, dtype and device, shapes, the derived seeds and their replay, training with SGD, Adam and LBFGS,state_dict,deepcopyandfrom_trained),test_torch_import.py(the import without PyTorch, the wheel's module, the extra's floor against CI's pin),test_qml_native.py'sTestModel(num_observables, pickle anddeepcopy, an edited spec rejected),test_qml_native_initial_point_final_shots.py(fit'sinitial_pointandfinal_shots: every rejection before the CUNQA seam and their order, the refusal offinal_shotswithexact=True, where each optimizer starts, a model read back withqml.loadtrained on, and the final re-evaluation on every sample, minibatches included, with its shots and every sample at the seam),test_typing_stubs.py'sTestFitTypes(the stub types of both),TestPrimitiveTypes(eachwrt's result type, forqml.jacobianandqml.vjp),TestKernelTypes(kernel_matrix's) andTestTorchTypes(the layer's inline types), the native QML cases oftest_interrupt.py(Ctrl+C duringfit, with and without acallback, duringqml.jacobianandqml.vjp, exact and sampled, and inside one long exact block, and duringqml.kernel_matrix, exact and sampled; the minibatch rescore runs with the GIL released),test_qml_adjoint.py(the adjoint and the parameter-shift fallback give the sameqml.jacobian,qml.vjpandfitwith Adam, the fallback logged, and no memory for one statevector the exact path's error; the same comparison for theQuantumLayerbackward is intest_torch_quantum_layer.py),TestNativeQmlChecksRaiseItintest_configuration_errors.py(every check offit,predict,run,qml.expval,qml.jacobian,qml.vjpandqml.kernel_matrixis apolypus.ConfigurationErrorraised before any CUNQA call, a negative or oversized execution integer included, by name and value,nodesandcores_per_qpuoff CUNQA too,qml.vjp's cotangent checked right afterparams, and a primitive, the kernel included, runs every block on one allocation),test_qml_native_execution_ints.py(the execution integers of the same entry points: abool(NumPy's too), afloat, astr, a complex andNoneaTypeErrorbefore any CUNQA call, NumPy integers reaching CUNQA as the integers they hold and refused by their value, where each range sits in the order of the checks, an argument's range and minimum before the next argument's range, the largest value of each type passing its range,0keeping its message and its acceptance off CUNQA, a negativenodesorcores_per_qpuwith the message of0on CUNQA and its type's bound elsewhere, the signatures still showing their defaults, andDataset.train_test_split'sseed: a plainValueError, aTypeErrorfor abool, NumPy's too, a NumPy seed giving the same split), and theModel.fitcases oftest_callback.py(itscallback'sTypeErrorbefore the CUNQA seam and afterfinal_shots, one call per iteration for every optimizer, Adam'sevaluations, a stop that still sends the final batch, an exception raised as itself, with no call or circuit after it and no final batch, a result unchanged by a callback that never stops).
C-12 · Call trace (trace= / POLYPUS_CALL_TRACE, JSON Lines schema v1)¶
polypus.train and polypus.run_quantum_circuit can write a call trace of a
run: a JSON Lines file that records how the run called its planner, its
backend, its optimizer and QNG's metric, with sizes, indices, times and
outcomes only. It shows how many batches and backend calls a run made, how
many circuits and shots each carried and how long each took, without changing
the run. The trace needs no Python and lives in the trace module of
polypus-orchestration: src/trace.rs holds the schema's types and
CallTracer, which creates, writes, caps and closes the file, and
src/trace/decorators.rs the four decorators that record the calls
(TracingPlanner, TracingBackend, TracingObserver and TracingVariance).
TrainFlow and RunCircuitFlow take the tracer in their trace field. The
edge (crates/polypus/src/bindings/call_trace.rs) opens the trace from the
trace argument or from POLYPUS_CALL_TRACE, and closes it with the status
Python sees.
trace is keyword-only and defaults to None. It takes a str or an
os.PathLike whose path is a str (the stubs type it
Optional[Union[str, PathLike[str]]]); any other value, a bytes path
included, is a TypeError raised before anything runs.
The format¶
- (a) Lines, clock and closed fields. A trace is UTF-8 JSON Lines: one JSON
object per event, each line ended by
\n. Therunheader is the first line andendthe last. Everytis in nanoseconds sincet0, the moment the tracer was created, on a monotonic clock, and everydtis a duration in nanoseconds; the wall-clock time appears only in the header, ast0_unix_ns. The fields are closed: each line has exactly the fields itsevhas in the table below, in that order, and a reader ofv: 1rejects a line with any other key, so a new field means a new version.
ev |
One line per | Fields |
|---|---|---|
run |
run, first | v (1), ev, flow ("train" or "run_circuit"), id (the run's effective id), polypus (the version that ran it), method (the optimizer; null for "run_circuit"), dims (the parameters it optimizes; null for "run_circuit"), backend, infrastructure, n_qpus, shots (per circuit), seed (the effective seed; null for a run without one, that is run_quantum_circuit on qmio, while train always has one), t0_unix_ns |
batch |
planner call that runs circuits: evaluate, execute or execute_replicas |
ev, k (the batch's index in the run, from 0), op (the method), n (circuits), shots (per circuit), t, dt, ok (whether it succeeded) |
wave |
backend call that runs circuits: run_circuits or run_shots_distributed |
ev, k (its batch; null for a call outside a planner batch, which the flows never make), w (its index in the batch, from 0), op, n (circuits; replicas for run_shots_distributed), shots (the shots per circuit asked for in that call; for run_shots_distributed, the sum of replicas), t, dt, ok, and for run_shots_distributed only, replicas (the shots of each replica) |
iter |
optimizer iteration | ev, i (the iteration, from 1), evals (candidates scored so far), batches (the batches recorded before it), best (TrainProgress.best_fitness; null if it is not finite), t (when the optimizer reported the iteration, taken before the callback runs) |
metric |
call to QNG's metric (a VarianceOracle) |
ev, n (the elements asked for: 1 for variance, dims for variance_diagonal), t, dt |
end |
run, last | ev, status (h), batches, waves, circuits (the sum of the batches' n), truncated (f), t |
A batch's wave lines come before its batch line, which is recorded once the
batch returns. The counts of end cover every event recorded, those a size cap
kept out of the file included (f): its batches, waves and circuits equal
the batch lines, the wave lines and the sum of the batches' n unless
truncated is true. The JSON Schema below gives
each line's fields, their types and their ranges, but two rules of the table
are beyond it, so a reader that validates with the schema alone accepts a line
that breaks them: the order of the fields, which
header_and_events_serialize_to_schema_v1_lines pins, and replicas being on
the run_shots_distributed waves and on no other line, which the Python tests
check with check_trace (tests/python/call_trace.py).
- (b) The trace changes nothing. With or without a trace, a run returns the
same result, bit for bit (
TrainResult,RunResult), raises the same error and makes the same calls to its backend, with the same arguments, seeds included, in the same order. A traced run is always observed: it gets aTracingObservereven without acallback, so it takes C-5's observed path, whose outcome an observer that never stops the run leaves bit for bit the same. Its calls to the backend stay the same as long as the run's oracles stop running circuits once a failure is recorded, as those ofpolypus-evaluationdo: an observed run stops at the end of the iteration in which a failure was recorded (C-5). - (c) Every method is forwarded. Each decorator forwards every method of
its trait to what it wraps, with the same arguments, and returns what that
returns, error included, the methods the trait gives a default included:
TracingBackendthe 10 ofQuantumBackend,TracingPlannerthe 5 ofPlanner,TracingVariancethe 2 ofVarianceOracleandTracingObserverthe 1 ofTrainObserver. A decorator that kept a default would make other calls than the untraced run: the defaultrun_shots_distributedwould call the wrapper'srun_circuits, and the defaultvariance_diagonalwould callvarianceonce per element. A method added to one of these traits gets its forwarding, and its test, in the same PR.
Opening, naming, capping and closing¶
- (d) Opening. The
traceargument wins overPOLYPUS_CALL_TRACE. The file is created new (create_new, that isO_EXCL): whatever is already at the path, a symbolic link included (even a dangling one), is left as it is, never overwritten or followed. On Unix the file's mode is0640, narrowed by the umask. The trace never creates a directory. If the file cannot be created (something is at the path, its directory does not exist, the process may not write there), the run logs one warning,call trace off, with the run's id, the path and the error, and goes on without a trace. The trace is opened before the backend is created, so its clock counts the backend's start-up (on CUNQA, raising the QPUs), and every way out of the run from there closes it (h). - (e) File names from the variable. Unset or empty,
POLYPUS_CALL_TRACEis off. Otherwise, for a run whosetraceisNone, it names the directory where the run writes its trace, in a file of its own:<id>-<pid>-<n>.jsonl, fortrainandrun_quantum_circuitalike, where<id>is the run's effective id (theidof its result and of its header),<pid>is the process's id and<n>counts, from 0, the traces the variable named before in the process. The effective id ends in a UUID v4, and that is what keeps apart the files of different runs:<pid>and<n>repeat among the processes that share a directory (in two containers, on two hosts, or once the system hands a pid on), and anyone who can list the processes knows them. Every character of<id>outside[A-Za-z0-9._-]becomes_, so the name stays inside the directory whatever the id holds, and an id longer than 100 characters keeps its first 100, followed by-and eight hexadecimal digits of a hash of the whole id (the low 32 bits of the 64-bit FNV-1a of its UTF-8 bytes), so two ids that share their first 100 characters still get different names. - (f) Size cap.
POLYPUS_CALL_TRACE_MAX_MBcaps every trace, in MiB (2^20 bytes): a whole number, at least 1, in ASCII digits alone, without a sign, spaces or a unit, whose size in bytes fits in 64 bits (so below 2^44 MiB); unset, the cap is 512 MiB. An invalid value is logged with one warning per process and ignored, so the default applies. The header counts toward the cap. An event that would take the trace past it is counted but not written, and neither is any event after it; theendline is written regardless, with"truncated": true, so the file never grows past the cap plus itsendline. - (g) Write failures. Recording never fails the run. The first write error
(a full disk, an I/O error) logs one warning,
call trace stopped, and stops the trace: nothing more is written,endincluded. A trace without anendline is incomplete, as is the trace of a process that was killed; its whole lines can still be read, up to the first that is not JSON. - (h) Status. The
statusofendis the outcome Python sees:"ok"when the run returns its result;"cancelled"when it raisesKeyboardInterrupt, as Ctrl+C does (it reaches the edge as theKeyboardInterruptofcheck_signalsinside a backend error, not as a cancelled run), and so do a cancelled run (InfrastructureError::Cancelled) and an aborted one (BackendError::Aborted);"error"for any other exception, one raised before the first batch included, such as by creating the backend; and"aborted"when nobody closed the trace: aCallTracerdropped withoutfinishwrites itsendline with that status. Only the firstfinishwrites. - (i) Content. A trace holds the fields of the schema and nothing else: never circuits, parameters, counts, environment variables or paths.
- (j) Cost. Without a trace nothing is installed: the flows run on the
run's own planner, the same
Arc, and add no decorator and no observer. With one, each line is serialized into one reused buffer and written through a 64 KiB buffer, flushed only after the header and when the trace is closed, behind one mutex per trace, uncontended in practice. The event lines (batch,wave,iter,metric) are written by a hand-written encoder that produces exactly the bytesserde_jsonwould, whichevent_lines_encode_as_serde_json_doesandevent_lines_encode_as_serde_json_does_for_random_valuescheck.
JSON Schema of version 1¶
The schema, exactly. tests/python/call_trace.py reads it from this block
(load_schema), and the Python tests read every trace with its read_trace,
which validates every whole line against it.
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "polypus-call-trace-v1",
"title": "Polypus call trace, version 1: one JSON object per line",
"oneOf": [
{"$ref": "#/$defs/run"}, {"$ref": "#/$defs/batch"}, {"$ref": "#/$defs/wave"},
{"$ref": "#/$defs/iter"}, {"$ref": "#/$defs/metric"}, {"$ref": "#/$defs/end"}
],
"$defs": {
"run": {
"type": "object", "additionalProperties": false,
"required": ["v", "ev", "flow", "id", "polypus", "method", "dims", "backend", "infrastructure", "n_qpus", "shots", "seed", "t0_unix_ns"],
"properties": {
"v": {"const": 1},
"ev": {"const": "run"},
"flow": {"enum": ["train", "run_circuit"]},
"id": {"type": "string"},
"polypus": {"type": "string"},
"method": {"type": ["string", "null"]},
"dims": {"type": ["integer", "null"], "minimum": 1},
"backend": {"type": "string"},
"infrastructure": {"type": "string"},
"n_qpus": {"type": "integer", "minimum": 1},
"shots": {"type": "integer", "minimum": 1},
"seed": {"type": ["integer", "null"], "minimum": 0},
"t0_unix_ns": {"type": "integer", "minimum": 0}
}
},
"batch": {
"type": "object", "additionalProperties": false,
"required": ["ev", "k", "op", "n", "shots", "t", "dt", "ok"],
"properties": {
"ev": {"const": "batch"},
"k": {"type": "integer", "minimum": 0},
"op": {"enum": ["evaluate", "execute", "execute_replicas"]},
"n": {"type": "integer", "minimum": 0},
"shots": {"type": "integer", "minimum": 0},
"t": {"type": "integer", "minimum": 0},
"dt": {"type": "integer", "minimum": 0},
"ok": {"type": "boolean"}
}
},
"wave": {
"type": "object", "additionalProperties": false,
"required": ["ev", "k", "w", "op", "n", "shots", "t", "dt", "ok"],
"properties": {
"ev": {"const": "wave"},
"k": {"type": ["integer", "null"], "minimum": 0},
"w": {"type": "integer", "minimum": 0},
"op": {"enum": ["run_circuits", "run_shots_distributed"]},
"n": {"type": "integer", "minimum": 0},
"shots": {"type": "integer", "minimum": 0},
"t": {"type": "integer", "minimum": 0},
"dt": {"type": "integer", "minimum": 0},
"ok": {"type": "boolean"},
"replicas": {"type": "array", "items": {"type": "integer", "minimum": 0}}
}
},
"iter": {
"type": "object", "additionalProperties": false,
"required": ["ev", "i", "evals", "batches", "best", "t"],
"properties": {
"ev": {"const": "iter"},
"i": {"type": "integer", "minimum": 1},
"evals": {"type": "integer", "minimum": 0},
"batches": {"type": "integer", "minimum": 0},
"best": {"type": ["number", "null"]},
"t": {"type": "integer", "minimum": 0}
}
},
"metric": {
"type": "object", "additionalProperties": false,
"required": ["ev", "n", "t", "dt"],
"properties": {
"ev": {"const": "metric"},
"n": {"type": "integer", "minimum": 0},
"t": {"type": "integer", "minimum": 0},
"dt": {"type": "integer", "minimum": 0}
}
},
"end": {
"type": "object", "additionalProperties": false,
"required": ["ev", "status", "batches", "waves", "circuits", "truncated", "t"],
"properties": {
"ev": {"const": "end"},
"status": {"enum": ["ok", "error", "cancelled", "aborted"]},
"batches": {"type": "integer", "minimum": 0},
"waves": {"type": "integer", "minimum": 0},
"circuits": {"type": "integer", "minimum": 0},
"truncated": {"type": "boolean"},
"t": {"type": "integer", "minimum": 0}
}
}
}
}
Enforcing test:
- Rust:
crates/polypus-orchestration/src/trace.rs:header_and_events_serialize_to_schema_v1_lines(a);create_never_overwrites_a_file_or_follows_a_symlinkandtrace_file_is_created_0640_or_stricter(d);size_cap_truncates_and_still_closesandworst_case_trace_fits_two_megabytes(f);write_failure_warns_once_and_leaves_no_endanda_transient_write_error_writes_nothing_more(g);trace_drop_writes_aborted,drop_failure_logs_one_error,finish_is_written_onceandfinish_stamps_the_end_after_a_record_in_progress(h);crates/polypus-orchestration/src/trace/decorators.rs:planner_trace_records_every_batch,a_backend_wrapped_outside_a_batch_has_no_kanditer_is_stamped_before_the_observer_and_metric_spans_the_oracle(a);traced_calls_return_what_untraced_calls_return(b);tracing_backend_forwards_every_method,tracing_planner_forwards_every_method,tracing_planner_passes_on_the_callers_cancel_token,tracing_observer_forwards_every_callandtracing_variance_forwards_both_methods(c);crates/polypus-orchestration/src/flow/trace_tests.rs:trace_matches_method_shape,trace_iter_and_metric_events_are_exact,run_circuit_flow_traces_its_replicasandmethod_name_labels_every_method(a);trace_does_not_change_the_outcomeandtrace_keeps_the_error_and_the_backend_calls_of_a_failed_run(b);trace_size_cap(f);trace_survives_write_errors(g);trace_off_installs_nothing(j);crates/polypus-orchestration/tests/conformance_with_trace.rs:conformance_with_trace, the wholepolypus-backend-conformancebattery on the native backend wrapped in aTracingBackend(c);crates/polypus/src/bindings/call_trace.rs:trace_file_name_is_sanitizedandfile_name_hash_is_fnv1a_64(e);max_mb_parses_whole_mebibytes(f);run_status_follows_the_python_errorandan_interrupt_inside_a_backend_error_is_cancelled(h).- Python:
tests/python/test_call_trace.py:test_trace_is_a_keyword_only_argument_that_defaults_to_none,test_a_trace_that_is_not_a_path_raises_before_anything_runsandtest_a_bytes_trace_path_raises_before_anything_runs(the argument);test_trace_header_fields,test_run_quantum_circuit_traceandtest_qng_metric_events_match_variance_calls(a);test_trace_does_not_change_results(b);test_same_trace_path_twice_keeps_the_first_fileandtest_a_trace_in_a_missing_directory_runs_without_a_trace(d);test_reader_stops_at_last_complete_line(g);test_trace_status_follows_the_outcomeandtest_an_error_before_the_first_batch_closes_the_trace_with_error(h);tests/python/test_call_trace_cunqa.py:test_cunqa_trace_forwardingandtest_cunqa_train_trace_forwarding(b, c: the same calls and seeds at the CUNQA seam,run_shots_distributedincluded, with and without a trace);test_a_failing_cunqa_job_closes_the_trace_with_error(h);tests/python/test_call_trace_process.py:test_an_existing_path_or_symlink_is_left_alone_with_one_warningandtest_trace_file_mode_is_0640(d);test_env_mode_writes_one_file_per_run,test_a_file_named_after_the_pid_alone_does_not_stop_the_trace,test_runs_with_the_same_pid_and_count_get_different_names,test_the_trace_argument_wins_over_the_variable,test_env_mode_creates_no_directory,test_an_empty_variable_is_offandtest_trace_id_is_sanitized(d, e);test_max_mb_caps_the_traceandtest_an_invalid_max_mb_is_warned_about_once_and_ignored(f);test_killed_run_leaves_a_readable_trace(g);test_trace_contains_only_schema_fields(i);test_native_trace_independent_of_budget(thebatchlines of a native run are the same whatevern_qpus, memory budget and threads, as C-7 requires; only its waves follow the memory budget);tests/python/test_call_trace_schema.py:test_trace_schema(the traces of every optimizer and of a circuit run, on one QPU and on several, validate against the schema above),test_the_schema_rejects_what_v1_does_not_allowandtest_read_trace_validates_every_whole_line_that_is_json(a);tests/python/test_typing_stubs.py:TestTraceType(the stub type oftrace, and the training guide's example type-checks);tests/python/test_interrupt.py:test_trace_on_interrupt(h: Ctrl+C during a traced run closes its tracecancelled, a complete trace that validates against the schema).