Changelog¶
All notable changes to Polypus are documented here. The format follows
Keep a Changelog and the project uses
Semantic Versioning. While the version is 0.x, a minor
release may contain breaking changes; they are marked BREAKING below
(Conventional Commits !).
Entries were curated from the Conventional Commits history. Releases before 0.6.0 predate the convention and are summarised by hand.
Unreleased¶
0.9.0 - 2026-11-30¶
Upgrading from 0.8¶
Breaking changes are marked BREAKING under Changed, Removed and Fixed. Where to look first:
- Python users. The native QML API is stricter: a bool or NumPy
bool_where it takes a count or an execution integer (num_qubits,reps,shots,seed,batch_size, ...) is aTypeError(#571, #607); a complexx,yory_trainis aTypeErrorinstead of losing its imaginary part (#602); a model is limited to 1 000 000 qubits and 4 000 000 gates (#572); andAnsatz.conv(..., pairing="odd_pairs")below three active qubits is aValueError(#631).qml.loadrefuses saved models that break these rules. An explicitseedof2**63or more withbackend="aer"orinfrastructure="cunqa"raisespolypus.ConfigurationError: passseed & (2**63 - 1)to replay such a run (#393). On Linux, a native circuit of 31 to 40 qubits runs when the memory budget holds it and raisespolypus.InsufficientMemoryErrorotherwise (#428). The internalpolypus_pythonpackage dropstest_connectionand the unreadLocal(num_qpus=...)arguments (#419). - Rust users.
polypus-physics:PauliAxis,PauliTermandPauliSummoved tohamiltonians::pauliand became multi-qubit,PauliSumis built withPauliSum::new,photon_polarization_hamiltonianreturns aResult, andPhysicsErroris#[non_exhaustive]with new variants (#529, #535).polypus-qml:QmlError,ValidationErrorandLayerhave new variants (#501, #504, #505, #513, #570, #572, #631).OptimizationOutcomehas astop_reasonfield (#431),TrainFlowandRunCircuitFlowatracefield (Nonekeeps the old behaviour), andpolypus_sim::MAX_QUBITSis 40 (#428). - Build. The
qmiofeature needs Rust 1.89 (zeromq0.7, #383); the default features still build with Rust 1.85. - Third-party backend authors. Depend on
"0.9".polypus-backendhas only additions, such asshot_groups(#419) and the memory-budget helpers of #428.
Added¶
polypus_backend::shot_groupsis public: it splits a per-replica shot list into runs of equal shot counts, as(first replica, shots, replicas), the grouping the defaultQuantumBackend::run_shots_distributedand the CUNQA backend submit by, for a backend that overrides that method (#419).- The native simulator now goes beyond 30 qubits where the memory budget
allows it (#428). Up to
polypus_sim::MAX_QUBITS= 40, a known budget (POLYPUS_MEM_BUDGET, or the RAM/cgroup limit detected on Linux) decides: a statevector that fits runs, one that does not is refused withpolypus.InsufficientMemoryErrorbefore anything is allocated. Where no memory limit is detected (macOS, Windows) statevectors still stop at 30 qubits with the same error as before, whose message now namesPOLYPUS_MEM_BUDGETas the way to lift it. A directpolypus-simcaller gets the newSimError::AllocationFailedinstead of an abort when the system refuses a statevector's memory. Calibration still reports31for never (so caches keep their meaning), and the newCalibrationResult::parallel_threshold()andCalibrationOutcome::parallel_threshold()give the value to set as a simulator'sparallel_threshold, with never asusize::MAX, now that 31-qubit circuits exist. TrainResult.stop_reasonandTrainResult.n_evaluationsontrain,qml.trainandModel.fit.stop_reasonnames what ended the optimizer's loop:"iteration_budget","evaluation_budget"(L-SHADE's schedule,External'smax_evaluations),"fitness_tolerance","parameter_tolerance"(PSO),"degenerate"(CMA-ES),"optimizer_finished"(External's emptyask()) or"callback".n_evaluationscounts the candidates scored as a fitness, asTrainProgress.evaluationsdoes, plus the re-score ofbest_paramson the whole training set when a gradient-free optimizer trains on minibatches; the shifted circuits of an exact gradient (Adaminqml.Model.fit) and the final batch are not counted. In Rust:polypus_optimizers::StopReason,OptimizationOutcome::stop_reasonandTrainOutcome::n_evaluations. Seeded results are unchanged (#431).- Typed execution targets:
polypus.Aer,Native,Cunqa,QmioandRegistered, each checking its own fields when built (exceptsim_method, which Aer checks when the run starts), and atarget=keyword onrun_quantum_circuit,train,qml.trainandqml.predictthat replacesinfrastructure,backendand their provider arguments (passing one of those next to it is aConfigurationError, exceptbackendorsim_methodleft at its default). Strings stay as shorthand; every acceptedinfrastructure/backendspelling now resolves through one alias table with unchanged errors.infrastructure(and, fortrain/qml.train,nodes,cores_per_qpuandid) now defaults toNoneso a call withtarget=can omit them; withouttarget=they are still required (#434). polypus.log_to_python()forwards the Rust core's log records to Python'slogging, as an alternative topolypus.init_logger()(only one of the two can be installed per process). Each record goes to the logger named after the Rust module that emitted it underpolypus(polypus_optimizers::utiltopolypus.optimizers.util), sologging.getLogger("polypus")sets the level, handlers and format of everything Polypus logs. Records carry the Rust file and line, the levels are read from Python at the start of each call, a disabled record never takes the GIL, and anERRORorWARNINGrecord emitted while the interpreter is shutting down goes to stderr as one fixed line instead of being lost (#458).polypus.qml.Model.num_observables, the readout's observables (the columns ofqml.expval), and pickling ofModel, socopy.deepcopyworks: it travels as the JSON of its spec, rebuilt through the checks ofqml.load(#502).polypus.torch.QuantumLayer(model, *, initial_params=None, seed=None, ...), atorch.nn.Moduleover a nativeqml.Modelfor hybrid quantum-classical networks: forward =qml.expvalover the batch, backward = oneqml.vjpcall with the incoming gradient (parameters, inputs or both; #559), so it trains with anytorch.optimoptimizer; float32 networks work as is (the computation is float64 on the CPU; a complex input is aTypeError, #602), and aseedderives one per backend call so a training replays.polypus.torch.from_trained(trained, ...)starts one from aTrainedModel. PyTorch is the new optional extrapip install "polypus-quantum[torch]"(torch>=2.14.1,<3);import polypusdoes not import it (#502). Seeexamples/qml_torch_hybrid.py.- Exact gradients of native QML by adjoint differentiation (#503): with
exact=Trueon the native backend,Model.fit's Adam gradient,qml.jacobianandpolypus.torch.QuantumLayer's backward pass take about three simulations per row (and observable) whatever the number of parameters, instead of two circuits per trainable gate; no API changes. The result is the parameter-shift gradient to rounding; shots keep the parameter shift, and so does exact mode when the memory budget holds one statevector of the model's width but not the two the adjoint needs (logged atinfoonce per fit orqml.jacobiancall). A Ctrl+C now also stops an exactqml.jacobianinside a block. Inpolypus-sim:StatevectorSimulator::adjoint_gradient,AdjointGradient,ADJOINT_STATEVECTORSand fourSimErrorvariants (GateIndexOutOfRange,NotDifferentiable,PartialMeasurement,NonFiniteWeight). Inpolypus-qml:QmlProblem::adjoint_runs/gradient_from_adjoint,JacobianBlock::adjoint_runs/num_adjoint_runs/jacobian_from_adjoint(andExpectationJacobian's),AdjointRunandDiagonalObservable. Inpolypus-infrastructure:NativeStatevectorBackend::adjoint_fits/run_adjointandAdjointTask.benchmarks/bench_adjoint.pymeasures it. polypus.qml.kernel_matrix(encoder, x1, x2=None, *, ...), the fidelity quantum kernelK[i, j] = |⟨φ(x1_i)|φ(x2_j)⟩|²of a nativeEncoderas afloat64NumPy array, ready for scikit-learn'sSVC(kernel="precomputed"). Withexact=Trueit takes the inner products of the native simulator's statevectors, each state simulated once when they fit in the memory budget; with shots, the0…0frequency of one compute-uncompute circuit (U(x1_i)thenU(x2_j)†) per entry. Withoutx2only the upper triangle, diagonal included, runs (N(N+1)/2circuits) and the matrix is symmetric bit for bit; the diagonal is executed, not set to 1. It takesqml.expval's execution arguments and rules, checks everything before a backend exists (a complex value inx1orx2is theTypeErrorqml.expvalraises for it, #602), and runs the pairs in blocks over one backend per call. Inpolypus-circuit:ConcreteCircuit::inverse,CircuitError::NotInvertible, andGateInstruction::push_inverse, public: the one inverse table of the workspace, which the native simulator's adjoint gradient now steps back through too (csx,rc3xandc3sqrtxare inverted through their decomposition). Inpolypus-qml:FeatureMap,FeatureStatesandFidelityKernel, and the variantsValidationError::TrainableLayerInFeatureMap,QmlError::KernelTooLargeandQmlError::StateWidthMismatch. Inpolypus-infrastructure:NativeStatevectorBackend::fidelity_matrix, which counts its matrix against the memory budget and, with room for one statevector beside it but not two, computes each entry from one statevector instead of refusing. Inpolypus-backend:InsufficientMemoryForResultand theBackendError::InsufficientMemoryForResultvariant (BackendErroris#[non_exhaustive]), raised in Python aspolypus.InsufficientMemoryErrorwhen a result leaves no room for its statevectors. Seeexamples/qml_kernel_svc.py(#504).polypus.qml.Ansatz.strongly_entangling(reps, ranges=None, entangler="cx"), PennyLane'sStronglyEntanglingLayers: per layer, a general rotation on every qubit, emitted asRz(φ),Ry(θ),Rz(ω), in that order, so the exact parameter-shift gradient still applies, then an entangler ("cx"or"cz") from each qubitito(i + r) mod n, with PennyLane's default ranges or one per layer;3·n·repsparameters. A range outside1..=n−1for the qubits active at that point is aValueErrorat the call, and the layer saves and loads withTrainedModel.save/qml.load(format version still 1). Inpolypus-qml:StronglyEntanglingAnsatz,Layer::StronglyEntangling,QuantumModel::strongly_entanglingand theValidationErrorvariantsStronglyEntanglingRangesLengthandStronglyEntanglingRangeOutOfBounds. The QML guide shows howEfficientSU2andBasicEntanglerLayersmap ontohardware_efficient(#505).- Multi-qubit Pauli sums and an exact H₂ Hamiltonian in
polypus-physics(#529), the reference for molecular simulation (#528). Inhamiltonians:PauliString(text form"X0 X1 Y2 Y3", product with aPhase),PauliSum::new/simplified/chop;PauliSum::to_dense_real,eigenvaluesandground_energy(little-endian basis, up toMAX_DENSE_QUBITS= 10, real matrices only; symmetric to withinSYMMETRY_TOLERANCErelative to the largest entry);FermionOperatorandFermionHamiltonianfrom spatial integrals (spin-orbitals in block order; integral symmetries checked toINTEGRAL_SYMMETRY_TOLERANCEand symmetrized);FermionOperator::to_qubitswithQubitMapping::JordanWignerorParity(Hermitian to withinHERMITICITY_TOLERANCEtimes the sum of the operator's |coefficients|);PauliSum::taperandparity_reduction_qubits, which fix the parities ofN↑andN, not their values (exact for H₂; sector diagonalization for larger molecules is #535). A newchemistrymodule: STO-3G integrals over normalized s-type contracted Gaussians andH2MoleculeinH2Encoding::JordanWigner(4 qubits) orParityTapered(2 qubits), which implementsPhysicsHamiltonian. Validated against PySCF/OpenFermion data inreference-data/h2-sto3g/(FCI at 0.7414 Å: −1.1372701747 Ha).constants::BOHR_RADIUS_ANGSTROM. New dependency:libm(erffor the Boys function). - Measuring a sum of multi-qubit Pauli strings from counts, in
polypus_observable:PauliandPauliMask(a Pauli string as twou64bitmasks, up toMAX_QUBITS= 64 qubits);group_qubit_wise, a greedy qubit-wise-commuting grouping into aGroupingofMeasurementGroups, each with its basis rotations (BasisRotation::HorBasisRotation::SdgThenH) and its reducer, while identity terms go toGrouping::constant; andParityObservable, aCostObservableforZstrings of any weight evaluated by bit parity, withexpectation_from_probabilitiesfor exact statevector probabilities. AΣ|c|·|scale|aboveMAX_WEIGHT_BOUNDis rejected, so no result can overflow, and counts whose total overflowsu64are an error (#530). - Training a cost given as a sum of multi-qubit Pauli strings, such as a
molecular Hamiltonian, in
polypus-evaluation(Rust; Python bindings follow in #532):PauliSumOracleFactory::new(template, terms)checks a native, measurement-free template and the(coefficient, PauliMask)terms, groups them into qubit-wise-commuting groups, and builds aPauliSumOraclethat measures each candidate once per group (the template, the group's basis rotations, a full measurement) with the run's shots, orfinal_shots, and returns the energy with its sign flipped, since the optimizers maximise. A candidate therefore costs one circuit and the run's shots per group. Invalid input is aPauliSumOracleError. The design is ADR 0009 (#531). - Generic
Z₂-symmetry tapering inpolypus-physics:PauliSum::z_symmetriesfinds every Z-type symmetry of a qubit Hamiltonian, andTaperingturns each into a singleZwith CNOTs and removes that qubit, with the values±1of a reference basis state or given explicitly;Tapering::for_sectordoes it for a molecule'sFermionHamiltonianin the Jordan–Wigner or parity encoding with the Hartree–Fock determinant's values (H₂, LiH and BeH₂ in STO-3G go from 4, 12 and 14 qubits to 1, 8 and 9).Tapering::applytapers any operator that commutes with the symmetries,tapered_basis_statemaps a basis state (e.g. a VQE initial state) into the tapered space, andPauliSum::restricted_eigenvaluesoverTapering::sector_basisgives the exact energy of an electron sector after tapering (#535). - Molecules beyond H₂ in
polypus-physics:chemistry::Fcidumpreads the integrals of an FCIDUMP file (as PySCF, Molpro or Psi4 write it; restricted, real integrals) into aFermionHamiltonian, with the electron sector(N↑, N↓)that itsNELECandMS2give; andFermionHamiltonian::sector_eigenvalues/sector_ground_energycompute the exact energies of one electron sector, the FCI energy of a molecule with given charge and spin projection (MS2; any total spin and spatial symmetry), from a matrix ofC(K, N↑)·C(K, N↓)determinants (up toMAX_SECTOR_DIMENSION= 2500) instead of the whole4^Kspace. Reference FCIDUMP files and FCI energies of H₂, LiH and BeH₂ in STO-3G, generated with PySCF, are inreference-data/fcidump-sto3g/(#535). - Adjoint differentiation of the gates the parameter shift has no rule for
(#561):
polypus-sim'sStatevectorSimulator::adjoint_gradientalso differentiatesCrx,Cry,Crz,Cp,Cu1,P,U1,U,UGate,U2,Cu3andCu(each of their angles, through its generator, the phase ofCu/Cu3relative to the control included) andU0(derivative0), with a new reduction kernel that gives the same bits with and without theparallelfeature. Inpolypus-qmla model with such gates is built like any other and gets its exact gradient, Jacobian and vector-Jacobian product by the adjoint (adjoint_runs,gradient_from_adjoint,jacobian_from_adjoint,vjp_runs), while the parameter-shift methods fail withQmlError::NoExactGradient, which names the instruction and points at exact mode; when exact mode cannot fit the adjoint's two statevectors it has no shift to fall back to, and the error says so (QmlProblem::check_shift_fallback,ExpectationJacobian::check_shift_fallback). No layer emits these gates yet, so nothing changes for a model built from Python. New:AngleRefinpolypus-circuit(re-exported bypolypus-sim), theSimErrorvariantAngleIndexOutOfRange, andpolypus-qml'stest-supportfeature (hidden constructors for the tests of the crates downstream; never enabled in a library or wheel build). polypus.qml.Ansatz.simplified_two_design(reps), PennyLane'sSimplifiedTwoDesign: anRyon every qubit, thenrepsblocks that applyCZand anRyon both qubits of each even pair and then each odd pair;n + 2·(n−1)·repsparameters for thenqubits active at that point, in PennyLane's order (initial weights, then(reps, n−1, 2)). OnlyRyandCZ, so the exact parameter-shift gradient still applies; one active qubit is the initial layer alone, whateverreps. The layer saves and loads withTrainedModel.save/qml.load(format version still 1). Inpolypus-qml:SimplifiedTwoDesignAnsatz,Layer::SimplifiedTwoDesignandQuantumModel::simplified_two_design(#505, #570).polypus-circuit'sGateInstruction::anglesandGateInstruction::angles_mutlist a built-in gate's angles inAngleReforder (none for a call of a declared gate) (#600). This order is now written in one place:polypus-sim's adjoint gradient andpolypus-qml's untying take it from there instead of listing it themselves. Their results do not change.- For Rust users, the workspace's seeded generator is public in
polypus_circuit::rng:SplitMix64withnew,next_u64,next_f64, the incrementSplitMix64::GAMMAand the finaliserSplitMix64::mix. The shot sampler, the per-call seeds of contract C-7, thepolypus-qmldataset splits and minibatches and the probe for colliding expression checksums all draw from this one definition, andpolypus_sim::SplitMix64is now a re-export of the same type. No seeded stream changes (#614). - For Rust users:
NativeStatevectorBackend::run_circuits_exact_on_stateshands a reader each circuit's amplitudes and key width instead of a map of its probabilities, andpolypus_qml::ExactStatereads them as that map, bit for bit, throughQmlProblem::read_state,CompiledModel::expectations_from_stateandCompiledModel::predict_from_state; no map is built (#628). - For Rust users:
NativeStatevectorBackend::run_circuits_exact_withreads each circuit's exact probabilities as soon as they are computed and keeps only what the reader returns;QmlProblem::read_probabilities,fitness_from_expectations,gradient_from_expectationsandadjoint_runs_from_expectations,ExpectationJacobian::jacobian_from_expectationsandJacobianBlock::jacobian_from_expectationstake those readings instead of the probability maps, with the same results bit for bit;ExpectationJacobian::modelreturns the model it differentiates (#645). - A call trace for
polypus.trainandpolypus.run_quantum_circuit(contract C-12): the keyword-onlytrace=(a path to a new file) orPOLYPUS_CALL_TRACE=<directory>writes one JSON Lines line per planner batch, backend wave, optimizer iteration and QNG metric call, with sizes and times only, capped byPOLYPUS_CALL_TRACE_MAX_MB(512 MiB by default). It never changes a result. - The call trace in Rust: the
tracemodule ofpolypus-orchestration, withCallTracer, which writes, caps and closes a trace, the types of its lines (TraceHeader,TraceEvent,RunStatus, …),DEFAULT_MAX_BYTES, and four decorators,TracingPlanner,TracingBackend,TracingObserverandTracingVariance, which record the calls they forward; andMethod::name(), the optimizer's name that a trace's header records. polypus.qml.expval(model, x, params, *, ...)andpolypus.qml.jacobian(model, x, params, *, wrt="params", ...)for a training loop of your own over a nativeModel: the expectation of every readout observable per row as afloat64NumPy array(rows, observables), and its exact parameter-shift Jacobian with respect to the parameters ((rows, observables, num_params)), the inputs of angle and IQP encoders ((rows, observables, features)) or both (wrt="both", a tuple). They takeTrainedModel.run's execution arguments, check everything before a backend exists (a complex value inx, Python's or NumPy's, is aTypeErrornaming its position, never cut to its real part; #602), and run the rows in blocks over one backend per call. Inpolypus-qml:CompiledModel::jacobianwithExpectationJacobian,JacobianBlock,JacobianandJacobianWrt,CompiledModel::expectations_from_counts/expectations_from_probabilitiesandnum_observables, andQmlError::NoInputGradient. Inpolypus-evaluation:window_sizeandcandidate_window_size, theQmlOracle's window policy, now public, which also sizes the primitives' blocks. Seeexamples/qml_expval_jacobian_loop.py.polypus.qml.vjp(model, x, params, cotangent, *, wrt="params", ...), the vector-Jacobian product ofqml.jacobianwith a(rows, observables)cotangent, what a reverse-mode backward pass needs:(num_params,)summed over the rows forwrt="params",(rows, features)for"inputs", the tuple for"both". Withexact=Trueit takes one adjoint run per row whatever the number of observables (qml.jacobiantakes one per row and observable), so the exact backward pass ofpolypus.torch.QuantumLayer, which now calls it, is up toKtimes cheaper for aK-observable readout; with shots it runsqml.jacobian's circuits and gives its contraction for the sameseed. The layer's gradients move in the last bits, no more: exactly, they come from one combined observable instead of one run per observable, and with shots the parameter product is summed in row order. The cotangent's shape is checked right afterparams(apolypus.ConfigurationError) and its values are read asx's are (a string,Noneor a complex value is the sameTypeError); aNaNor an infinity in it propagates as through the contraction, and changes only its own row's route.qml.jacobiandoes not change. Inpolypus-qml:Jacobian::vjp,JacobianBlock::vjp_runs/num_vjp_runs/vjp_weight_bounds/vjp_from_adjoint(andExpectationJacobian's),VjpandDiagonalObservable::weight_bound.benchmarks/bench_vjp.pymeasures it (#559, ADR 0008).
Changed¶
- BREAKING (build): the
qmiofeature needs Rust 1.89:zeromqgoes from 0.6 to 0.7, which raised its MSRV. Default features keep Rust 1.85. The QMIO reply-size cap is still checked after the reply is received; 0.7 has no receive size limit yet (#383). - BREAKING: an explicit
seed(theseedargument, or theseedof an optimizer such asDE(seed=...)passed totrainorqml.train) of2**63or more withbackend="aer"orinfrastructure="cunqa"now raisespolypus.ConfigurationError(aValueError) instead of reaching Qiskit Aer masked to 63 bits, which gave two seeds differing only in bit 63 the same counts; passseed & (2**63 - 1)to replay a run made with such a seed. The native backend still takes any 64-bit seed.polypus.torch.QuantumLayer(seed=...)masks the seed it derives for each call to 63 bits, so a seeded layer gives the same values as before on Aer and CUNQA; on the native backend the calls whose derived seed had bit 63 set now sample differently (#393). - For contributors: every workspace crate inherits a
[workspace.lints]table from the rootCargo.tomlthat deniesunsafe_codeandclippy::undocumented_unsafe_blocks, so the threeunsafesitesdocs/ENGINEERING.md§5 authorises are the only ones that compile, each with its own block-scopedallow.missing_docsis on in the crates that are already fully documented, andcargo denykeepspyo3out of the pure crates (#408). - CI reports how well the tests check the code, not only what they run: the
SonarQube Cloud workflow's coverage jobs write Rust line coverage per crate
in their summary, and a weekly
mutation.ymlrunscargo mutantsover the pure-Rust crates (report only) and comments the score per crate on a tracking issue. New tests catch the mutants that survived inpolypus-observable, CMA-ES and SHADE, andpolypus-backend's memory guard and planner, and property tests check the OpenQASM round trip and that the parallel kernels match the sequential ones on random circuits (#409). - BREAKING: on Linux, a native circuit of 31 to 40 qubits is no longer
refused with the qubit ceiling's
ValueError/polypus.NativeCircuitError: it runs if the memory budget holds it and raisespolypus.InsufficientMemoryError(not aValueError) otherwise. Above 40 qubits, and above 30 where no memory limit is detected, the ceiling error is unchanged. For Rust users,polypus_sim::MAX_QUBITSis 40 instead of 30, soStatevectorSimulator::default()andStatevector::newaccept up to 40 qubits; the 30-qubit fallback ceiling ispolypus_backend::mem_budget::FALLBACK_MAX_QUBITS(#428). The parallelism calibration cache keeps reading existing files as before. - BREAKING (Rust):
polypus_optimizers::OptimizationOutcomehas a new public field,stop_reason, so a struct literal of it outside its crate must set it (#431). - CUNQA: the seal looks up a family's QPUs with
get_QPUsonce instead of once per wave, and looks them up again afterqdropor a failed wave (#437). - BREAKING (Rust):
polypus_qml::QmlErrorhas two new variants,KernelTooLargeandStateWidthMismatch, so an exhaustivematchon it outside its crate must handle them (#504). - BREAKING (Rust):
polypus_qml::ValidationErrorhas a new variant,TrainableLayerInFeatureMap, so an exhaustivematchon it outside its crate must handle it (#504). - BREAKING (Rust):
polypus_qml::ValidationErrorhas two new variants,StronglyEntanglingRangesLengthandStronglyEntanglingRangeOutOfBounds, so an exhaustivematchon it outside its crate must handle them (#505). - BREAKING (Rust):
polypus_qml::Layerhas a new variant,StronglyEntangling, so an exhaustivematchon it outside its crate must handle it (#505). - BREAKING (Rust):
polypus_qml::QmlErrorhas a new variant,NoInputGradient, so an exhaustivematchon it outside its crate must handle it (#501). - BREAKING (Rust):
polypus_qml::ValidationErrorhas a new variant,NoFeatures, so an exhaustivematchon it outside its crate must handle it (#513). - BREAKING (Rust):
PauliAxis,PauliTermandPauliSummoved fromhamiltonians::photon_polarizationtohamiltonians::pauli; the old pathshamiltonians::photon_polarization::{PauliAxis, PauliTerm, PauliSum}no longer exist. Import them frompolypus_physics::hamiltonians(#529). - BREAKING (Rust):
polypus_physics::hamiltonians::PauliTermis{ coefficient, string: PauliString }instead of a single Pauli on one qubit (qubit,axis), andPauliSum's fields are private: build it withPauliSum::new, which validates, and read it withnum_qubits()andterms()(#529). - BREAKING (Rust):
photon_polarization_hamiltonianreturnsResult<PauliSum, PhysicsError>, rejecting non-finite parameters (#529). - BREAKING (Rust):
polypus_physics::error::PhysicsErrorhas new variants,InvalidPauliSum,UnsupportedOperation,InvalidFermionOperatorandInvalidIntegrals, so an exhaustivematchon it outside its crate must handle them (#529). - BREAKING (Rust):
polypus_physics::error::PhysicsErroris#[non_exhaustive], so amatchon it outside its crate needs a wildcard arm, and has two new variants,InvalidFcidumpandInvalidSector. Later variants will no longer be breaking changes (#535). - Exact native QML gradients are faster where a batch of them used to take the
parallel gate kernels (from 12 qubits on, on the 16-thread node measured): a
batch of two or more adjoint runs (
NativeStatevectorBackend::run_adjoint) now runs each one on the sequential gate kernels and leaves the cores to the runs themselves. Forking every short pass of a run onto the shared pool cost more than it saved, and that made the adjoint's cost jump from 10 to 12 qubits. On 16 threads with 8 rows,qml.jacobian(..., exact=True)is 2.3–6.6× faster at 12 qubits and 2.5–3.9× faster at 14, and an exactModel.fitepoch is 1.3–2.0× faster (benchmarks/bench_adjoint.py). From about 18 qubits on, a batch of two runs can be up to ~1.4× slower than before on the 12–16 threads measured, and on wider nodes a batch smaller than the thread count may lose more (#593). The results are the same bit for bit (#560). - The message of
QmlError::NoExactGradient, which reaches Python aspolypus.EvaluationError(fromModel.fit) orValueError(fromqml.jacobian), startsno exact gradient for this model:instead ofno exact parameter-shift gradient for this model:(#561). - An adjoint derivative is named by an
AngleRef(position,angle) instead of a gate position, so a gate with several angles can have one derivative per angle (#561). The adjoint API is new in this release (#503), so code written against 0.8 is not affected:StatevectorSimulator::adjoint_gradient'swrt,AdjointTask::wrtinpolypus-infrastructureandAdjointRun::wrtinpolypus-qmlare&[AngleRef]/Vec<AngleRef>. A Pauli rotation's angle isAngleRef::new(position, 0); its derivative is unchanged, bit for bit.SimErrorhas the new variantAngleIndexOutOfRange, andNotDifferentiablenow means a gate without angles or the call of a declared gate. - BREAKING (Rust):
polypus_qml::Layerhas a new variant,SimplifiedTwoDesign, so an exhaustivematchon it outside its crate must handle it (#570). - BREAKING: a bool is no longer accepted as a count of the native QML API
(
num_qubits,reps,ranges, a Pauli position,batch_size):Z(True),Encoder(True)orfit(batch_size=True)were read as1(andFalseas0); they are now aTypeError, asfinal_shotsalready was (#571). - BREAKING: a native QML model is now bounded in size before its circuit
is built.
polypus.qml.Encoder/Ansatzrefuse more than 1 000 000 qubits, and a layer that takes the model's gates past 4 000 000 is aValueErrorwhere it is added (or, for an encoder that meets more features than at construction, the error of the call that brings the data: apolypus.ConfigurationErrorinfit,predictandrun). Models over those limits that were accepted before, such ashardware_efficient(2**40)or an amplitude encoder over more than 20 qubits, are now refused, byqml.loadtoo. A count too large to fit in 64 bits now readslayer N needs more gates than fit in a usize. In Rust,polypus_qmlexportsMAX_MODEL_GATES,MAX_MODEL_QUBITSand theSizeLimitenum, andValidationErrorhas two new variants,ModelTooLargeandTooManyQubits, so an exhaustivematchon it outside its crate must handle them (#572). - Building Polypus from source needs maturin 1.9.4 or later (it was 1.9.2),
the first release that exports
PYO3_BUILD_EXTENSION_MODULEto the build (#599). - BREAKING: a bool is no longer accepted as an execution integer of the
native QML API (
shots,n_qpus,nodes,cores_per_qpuorseedofModel.fit,TrainedModel.predict/run,qml.expval,qml.jacobian,qml.vjpandqml.kernel_matrix, and theseedofDataset.train_test_split):shots=Truewas read as1(andFalseas0); it is now aTypeError, before any backend exists, as the counts of the native API andfinal_shotsalready were. A NumPybool_, which NumPy 2.0 still reads as1/0, is now aTypeErrortoo, there and in the counts of the native API (#607). polypus-loggerusesjiffinstead of the unmaintainedchrono(RUSTSEC-2026-0543) for its local timestamps; the log line prefix, the JSON"timestamp"field and the default log file name keep their format. For Rust users, the minimum supported versions rise tolog0.4.21 (every workspace crate) andserde1.0.221 (the crates that use it), the floorsjiff's optional dependencies need (#618).- BREAKING:
polypus.qml.Ansatz.conv(..., pairing="odd_pairs")below three active qubits is now aValueErrorat the call: there is no odd pair to act on, so no gate read the parameters it reserved.qml.loadand unpickling refuse a saved model with such a layer. To keep using one, delete the layer from itsspecand, for a saved trained model, also delete its 4 ("basic") or 3 ("cartan") entries fromparams, the ones right after the parameters of the layers before it: left in,loadfails on the parameter count, and deleting others shifts the values every later layer reads. Those entries were never read, so the model computes what it computed before. A convolution below two active qubits keeps raisingValueError, with a message that now names the convolution and its pairing (#631). - BREAKING (Rust):
polypus_qml::ValidationErrorhas a new variant,ConvNeedsQubits, whichConvLayer's planning returns for every qubit shortfall (including fewer than two active qubits, formerlyNotEnoughQubits), so an exhaustivematchon it outside its crate must handle it (#631). PauliSumOracle(#531) now runs a batch in windows of whole candidates, sized bycandidate_window_sizeas the QML oracle's are, so at mostwindow × groupsbound circuits are alive at once however large the population or the Hamiltonian; the expected values are unchanged, and a seeded run on the native backend gives the same values bit for bit (a backend seeded per call, such as Aer, now draws one stream per window). An empty batch no longer calls the planner, and a group whose counts do not total the shots asked for (contract C-3), an empty map included, is anEvaluationErrornaming the group and the candidate under any planner, not only the built-in ones, which already reject such counts; before, a planner of one's own could bias the energy silently.group_qubit_wiseleaves terms whose coefficient is exactly zero out of every group, as it does identity terms, so they no longer cost circuits; a Hamiltonian with nothing else to measure isPauliSumOracleError::NothingToMeasure(#667).- BREAKING: for Rust users,
TrainFlowandRunCircuitFlow(polypus-orchestration) have a new public field,trace: Option<Arc<CallTracer>>, so a struct literal must set it;trace: Nonekeeps today's behaviour. - For contributors: changelog entries go in
changelog.d/, one file per change, and the release pull request assembles them intoCHANGELOG.mdwith towncrier, so pull requests no longer conflict onCHANGELOG.md. See Changelog entries indocs/CONTRIBUTING.md. - For contributors: the CI, Hygiene and SonarQube Cloud workflows also run on
GitHub merge-queue groups, a prerequisite for enabling the queue on
main. Hygiene checks the queue's candidate commit againstmainwith the public rules; SonarQube Cloud skips its jobs there, since the quality gate already ran on the pull request and the push tomainreports on the merged commit. - For contributors: the Hygiene check also scans the messages of the commits
it analyses (merge base to head on pull requests, base to head on merge-queue
groups and pushes to
main) with the same public rules as file content, plus the private patterns onmain, and flags internalbahia<N>host names alongside login-node names. Commit messages admit no allow-list exceptions. - For contributors: the Hygiene check rejects a change to
CHANGELOG.mdwhileCargo.tomlcarries anX.Y.Z-devversion; entries go inchangelog.d/, and only the release pull request assembles them intoCHANGELOG.md.
Removed¶
- BREAKING (
polypus_python): the internalpolypus_pythonpackage no longer exportstest_connection, a placeholder that only printed a message, and its infrastructure classes no longer take or storenum_qpus,qubits_per_qpuandqpu_types, which nothing read: buildLocal()instead ofLocal(num_qpus=..., ...).polypusitself is unchanged (#419).
Fixed¶
- A seed drawn from OS entropy is now below
2**63, the range of Aer'sseed_simulator, so on a run's first call Aer receives the seed the run reports and a one-call run replays withAerSimulator(seed_simulator=seed); about half of the drawn seeds used to be above it (#393). - On Windows the gate-parallel calibration is now cached under
%LOCALAPPDATA%\polypus\whenXDG_CACHE_HOMEis not set. PowerShell and cmd define neitherXDG_CACHE_HOMEnorHOME, so the first native simulation of every process measured the threshold again and never saved it.XDG_CACHE_HOMEstill wins on every platform, and macOS and Linux are unchanged. A Windows user who hasHOMEset and an existing cache in%HOME%\.cache\polypus\measures once more, in under a second;calibrate_parallel_threshold()["cache_path"]shows the new location (#416). polypus.qml.Ansatz.hardware_efficientandreal_amplitudeswith a negativerepsraisedOverflowError, and with arepswhose parameter count does not fit in 64 bits aPanicException(whichexcept Exceptiondoes not catch); both, and any integer too large for a count, are now aValueErrorat the call that leaves theAnsatzas it was. A saved file edited to such a count fails the same way. Inpolypus-qml,QuantumModel::compilereturns aValidationErrorinstead of panicking (#505).- The native QML API now rejects samples with zero features.
qml.Dataset,Model.fit,TrainedModel.predict/run,Model.circuit/TrainedModel.circuit,qml.expval/qml.jacobian/qml.vjpandqml.kernel_matrixraise aValueError(apolypus.ConfigurationErrorwhere the entry point already raised one) saying that every sample needs at least one feature, where they used to run a model that never saw the data and predicted a constant. The amplitude encoder gets that message too, instead of the zero-norm one. Fewer features than qubits stays accepted (contract C-11, #513). - The OpenQASM 2.0 export of a barrier on every qubit in order and of the
measurements
q[k] -> c[k]of every qubit in order is now written asbarrier q;andmeasure q -> c;, the form the importer reads them back in, as the OpenQASM 3 export already did. Soto_qasm2(from_qasm2(to_qasm2(c)))is byte-identical toto_qasm2(c)for these circuits too (contract C-2), and the exported text of those two shapes changes for the same program (#568). - The rest of the native QML API's integer arguments followed: a negative or
oversized
num_qubitsofpolypus.qml.Encoder/Ansatz, or position ofZ/X/Y, raisedOverflowError, and the same position in a[(pauli, position), …]list (aReadoutobservable or anObservableterm) aTypeErrorthat did not name it; all are now aValueError, the list form naming the term or observable and the factor.Model.fitwith a negative or oversizedbatch_sizeraisedOverflowError; it is now thepolypus.ConfigurationErrorthat0already raised, before any backend exists. An object with__index__(a NumPy integer) is read as the integer it returns, which an out-of-range message shows. Another type is still aTypeError(#571). - A native QML model whose size fit in 64 bits but no circuit could hold was
accepted by its builder and only failed later, out of memory or time, in
circuit,bindorfit:Ansatz(2).hardware_efficient(2**40)built, and so did ahardware_efficient(reps, rotations=[])on two or more qubits, with no parameters butrepsblocks of entanglers.Ansatz(2**40).real_amplitudes(0)aborted the process on a failed allocation,Ansatz(2**62).real_amplitudes(0)raised aPanicException, and so didEncoder(64).amplitude_encoder(). All are now aValueErrorat the call, which leaves the object as it was, and so is a saved file edited to such a model. On a single active qubit, where it emits no gate at all, ahardware_efficient(reps, rotations=[])is still accepted, and building its circuit no longer takes time inreps(#572). - BREAKING: the native QML entry points of 0.8.0 refuse a complex value
instead of dropping its imaginary part: a complex
x(Model.fit,TrainedModel.predict/run,qml.Dataset,Model.circuit/TrainedModel.circuit),y(Model.fit,qml.Dataset) ory_train(train,qml.train) is aTypeErrornaming the value's position, whatever its imaginary part and whatever holds it. A NumPy complex array, or a NumPy complex scalar in a list, was accepted cut to its real part with aComplexWarning, while the same value as a Pythoncomplexwas already aTypeError(#602). - A negative or oversized
shots,n_qpus,nodesorcores_per_qpu(more than 4294967295) orseed(more than 18446744073709551615) ofModel.fit,TrainedModel.predict/run,qml.expval,qml.jacobian,qml.vjpandqml.kernel_matrixraisedOverflowError; it is now apolypus.ConfigurationErrornaming the argument and the value, before any backend exists, on every infrastructure; a negativeshots/n_qpus(andnodes/cores_per_qpuoncunqa) gets the message of0. The sameseedofDataset.train_test_splitis now aValueError. An out-of-range object with__index__(a NumPy integer) is shown as the integer it returns (#607). run_quantum_circuit,train,qml.trainandqml.predictwithinfrastructure="qmio"and a nativebackendname ("polypus") now reject a Qiskit circuit with QMIO's message instead of the native backend's, whose advice to usebackend="aer"does not apply on QMIO (#617).QuboObservableandIsingObservable(polypus.Quboandpolypus.Ising) panicked when the shot counts of one candidate added up to more thanu64::MAX; they now returnObservableError::Invalid, asParityObservabledoes, and a total of exactlyu64::MAXis still evaluated. They also evaluated toinfwhen finite coefficients added up pastf64::MAX(two linear terms of1e308); a QUBO whose(|constant| + Σ|linear| + Σ|quadratic|)·|scale|exceedsMAX_WEIGHT_BOUND(about4.9e288) is now rejected at construction, aValueErrorfrom Python, and an Ising cost is checked on its QUBO form, whose coefficients add up to as much as 9 times the Ising ones. Results of every accepted cost are unchanged (#625).- An exact run on the native backend (
exact=True) checked only its statevector against the memory budget, while it also held a vector of2^nprobabilities and a map of up to2^nresults per circuit: a dense 34-qubit run on a 512 GiB host passed the check and was then killed by the out-of-memory killer, with no Python exception. The probabilities vector is gone.TrainedModel.run(exact=True), which returns those maps, now counts them against the budget beside the statevectors in flight: one that would not fit raisespolypus.InsufficientMemoryErrorbefore it is allocated, after the run has dropped to one circuit at a time, while a sparse output stays cheap at any width; each map is freed as its Python dictionary is built, though those dictionaries (1.1 to 1.2 times the maps) are not counted. Exact training and gradients,qml.expval,qml.jacobian,qml.vjpandTrainedModel.predict(exact=True)build no map at all: they read each circuit's expectation values straight from its statevector, bit for bit what the map would give, so they need only the statevector budget, and the parameter-shift fallback of the exact gradient needs one statevector where the adjoint needs two. Under the fallback budget (no memory limit detected) nothing is refused, as before (#628). - The exact native path (
exact=True) kept the map of probabilities of circuits it only reads for a few expectation values: an exact gradient ofqml.trainorModel.fitheld one map per circuit of the gradient until the step ended (one per shifted circuit for the parameter-shift fallback, so on a dense output it needed far more memory than the adjoint gradient it replaces), the exact fitness one per circuit of a candidate window, the exactqml.expval,qml.jacobianandqml.vjpone per circuit of a block, andTrainedModel.predict(exact=True)one per row. Each circuit is now read as soon as its probabilities are computed and only its expectation values are kept, which also makes exact training faster; every result is unchanged, bit for bit.TrainedModel.run(exact=True)and the exact kernel, which return or read the probabilities themselves, are unchanged (#645). IsingObservable(polypus.Ising) reported the errors of its expanded QUBO as if they were about the caller's input. A finite field or coupling whose expanded coefficients overflowf64(-2h, or4Jfor a coupling nearf64::MAX) was reported as a QUBO "linear" or "quadratic coefficient … is not finite", and a sum aboveMAX_WEIGHT_BOUNDas a bareΣ|c|·|scale|, which can be up to 9 times the caller's own. The error now names the field or coupling (or the constant they fold into) that overflows and says the expanded QUBO cannot be built, and it reports the bound as the expanded QUBO's sum, saying how much each field and coupling adds to it. A variable whose expanded linear coefficient overflows while the-2hand-2Jon it are added up is named too. AΣ|c|that overflowsf64is reported as such, before the scale multiplies it, instead of asinforNaN"exceeding" the bound (withscale = 0the product wasNaN); this also changes the message ofQuboObservable,ParityObservableandgroup_qubit_wise. The error type (ObservableError::Invalid, aValueErrorfrom Python) is unchanged.
Documentation¶
- The
documentationlink of thepolypuscrate, and the site's and README's Rust API links, point at docs.rs, which keeps the API of each release; the rustdoc on the site under/rust/, built frommain, is linked as the unreleased API. For contributors, a rootjustfileholds every check CI runs and CI calls its recipes, sojust cireproduces them locally (just ci-alladds the MSRV, dependency-floor, packaging, semver, fuzz and Miri jobs); optional pre-commit hooks run rustfmt, ruff and nbstripout. ADR 0006 is marked accepted (#421). - The
ValueErrors ofpolypus.Qubo,polypus.Qubo.from_matrixandpolypus.Isingare now in the docstrings Python shows: they were written on the constructors, whose doc comments PyO3 does not expose, sohelp()never listed them. They now include the coefficient bound (sys.float_info.max / 2**65, about 4.9e288; checked on the expanded QUBO forIsing), and thepolypus.EvaluationErrorraised when one candidate's counts add up to more than2**64 - 1. The training guide states the bound. - The Qiskit Aer example of
examples/python-backend-template/worker.pypassed each request's seed toAerSimulator(seed_simulator=...)as is, though a registered backend receives any 64-bit seed and Aer rejects one of2**63or more, so a provider copying it would have failed on about half of a run's requests. It now masks the seed to 63 bits (seed & (2**63 - 1), keepingNone), and the protocol description in the worker, inworker_template.pyand in the backends guide says when to mask (#642). - The documentation site (MkDocs Material) is published at the Pages root,
with the rustdoc of every crate under
/rust/. Only the crate index pages of the old rustdoc URLs (.../polypus/<crate>/) redirect to.../polypus/rust/<crate>/; deeper rustdoc links change. - The site takes the Polypus cyan and octopus mark, Inter and JetBrains Mono served from the site itself (no third-party font requests), and a new landing page with a tabbed quickstart.
0.8.0 - 2026-10-30¶
Upgrading from 0.7¶
Breaking changes are marked BREAKING under Changed and Fixed. Where to look first:
- Python users. Python 3.10 or newer (#360),
qiskit<3andqiskit-aer<0.18(#362), CUNQA 2.4 or newer (#204). Seeded results differ from 0.7 on every backend (#348, #401, #410, #411,rand0.10): re-run stored baselines instead of expecting them to replay. Arguments that were ignored now raise:noise_model,sim_methodandbackendwhere they do not apply (#332, #334),patience=0inpolypus.DEandpolypus.CMAES(#467), and counts that sum to zero inexpectation_value(#227). Configuration errors arepolypus.ConfigurationError, still aValueError(#418), and Qiskit and Aer exceptions are raised aspolypus.BackendErrororpolypus.EvaluationError(#218). QMIO needsZMQ_SERVERoroptions={"endpoint": ...}, andrun_qc_in_qpu,run_qcs_in_qpuandrun_worker_qpu.pyare gone. - Rust users. The
polypuscrate has no default features (#414); the circuit types' fields are private (#349);GateInstruction,CircuitError,SimError,BackendError,OptimizerErrorandpolypus_orchestration::Methodare#[non_exhaustive], andEvaluationErrorhas new variants; the DE, PSO and QNG argument structs,DeConfigandTrainFlowhave new fields anddispatch_optimizera new argument (#395, #397, #410, #500); anOptimizerimplemented outsidepolypus-optimizersimplementsoptimize_observedinstead ofoptimize(#500);OracleFactory::build,templates::qft,Statevector::expectation_zandpolypus_sim::sample_projectedchanged their return types;BackendConfig::LocalandCunqahave nobackendfield (#230); thepolypus-physicssamplers take rand 0.10'sRng(#273). - Third-party backend authors.
polypus-backend,polypus-backend-conformanceandpolypus-subprocess-backendare on crates.io from this release; depend on"0.8". Registry options are typed (#293, migration indocs/backends.md), a backend gives each call of a run its own seed (#411, contract C-7),BackendErroris#[non_exhaustive]andcircuits::as_qasm2returns aResult(#350).
Added¶
- Native QML models in
polypus.qml:Model(encoder, ansatz, readout)built from anEncoderand anAnsatz(layer builders that check each call without the data, with data re-uploading inside the ansatz) and aReadout(observables, decision="raw", threshold=None), with the readout helpersZ/X/Y,PauliTerm(Z(0) @ Z(1)) andObservable(weighted sums).Model.fit(x, y=None, *, method, loss=None, ...)trains it on rows or aDataset(x, y=None)(an unlabeled dataset stays marked as such across a split) and returns aTrainResult: supervised with a named loss, or unsupervised maximising the readout; Adam gets the exact parameter-shift gradient;polypus.Rotosolveis accepted withloss="expectation"on a model whose trainable parameters each sit in one rotation, and is otherwise apolypus.ConfigurationErrorbefore anything runs, as intrain(#398);exact=Trueuses exact probabilities on the local native simulator;batch_sizetrains on minibatches.Model.bind(params)gives an immutableTrainedModelwhosepredictreturns the readout's decisions (intfor sign, threshold and argmax,floatfor raw) and whoserunreturns the counts per row, or anExactResultof probabilities withexact=True.TrainedModel.save(path)writes it as versioned JSON (read back bit for bit) andpolypus.qml.load(path)reads it, revalidating the model and its parameters; loading never runs code. Execution arguments have defaults, andbackend=Noneis the native simulator onlocal. Options are strings from closed sets.qml.trainandqml.predict, which run Qiskit circuits, reject anEncoderorAnsatzwithTypeError. polypus_backend::CallSeeds, which hands out the seed of each call a backend receives (the run's on the first, then one derived from it and the call's index), andpolypus_backend::stream_seed, the SplitMix64 map behind it and behind the native backend's per-circuit seeds (#411).polypus.DE(mutation_factor=None, crossover_rate=None): DE/rand/1/bin'sF, in(0, 2], andCR, in[0, 1];Nonekeeps 0.8 and 0.7. A value out of range, or any value withstrategy="shade"or"lshade", which adapt both, raisespolypus.ConfigurationErrorwhen the object is built or the attribute set. Rust:AlgorithmDifferentialEvolution::check_ratesand theDEFAULT_MUTATION_FACTORandDEFAULT_CROSSOVER_RATEconstants (#410).polypus.External(optimizer, max_evaluations), accepted bytrainandqml.train: runs an optimizer from outside Polypus, a library such as Optuna, Nevergrad or pycma or an object of your own, through Polypus's scheduler. The optimizer hasask(), which returns the next batch of rows (Noneor an empty batch when it is done), andtell(candidates, values), which receives that batch and its fitness, to maximise. Eachask()is one batch, spread over the QPUs. The run stops at an emptyask()(converged=True) or before a batch that would take it pastmax_evaluations, which is neither evaluated nor told, so the budget is never exceeded. A row that is notdimensionsfinite real numbers (aboolor a complex number is not one) raisesValueErrornaming its batch and row; a batch and a row are read only up to one row or value too many, so an endless iterator cannot hang the run. An exception fromask()ortell(),KeyboardInterruptincluded, is raised as itself.Externaltakes part in garbage collection, so an optimizer that refers back to it is freed.best_paramsis the best candidate Polypus measured,iterations_runcounts the batches, andfinal_shotsre-evaluates five candidates. The library owns its seed and its start:Externalhas noseed(the run's seed fixes the shot sampling) andinitial_pointraisesValueErrorbefore anything runs (#399).polypus.ask_tell, pure-Python adapters forpolypus.External:from_optuna(study, dimensions, batch_size, bounds=(0, 2π), initial_point=None), for example with Optuna's TPE sampler,from_nevergrad(optimizer, batch_size=None, initial_point=None)andfrom_pycma(es), which call each library's public ask/tell methods only and negate the values for a library that minimises; andAskTell, the protocol as atyping.Protocol. None of the three libraries is a dependency of Polypus, and the module imports none of them (#399); the pip extrasoptuna,nevergradandcma(pip install "polypus-quantum[optuna]") install one, from the version CI tests the adapters with up to the next major. An adapter'stellraisesValueErrorfor other candidates than the batch it handed out, or the same in another order, before the library is told anything. The Optuna adapter, anOptunaAskTell, hasclose(), which marks the trials of a batch handed out and never toldTrialState.FAIL, so that a budget that cuts a batch leaves no trialRUNNING(#467).- External optimizers in training runs (Rust,
polypus-orchestration):Method::ExternalwithExternalConfig. The CUNQA walltime warning projectsmax_evaluations / nbatches after a first batch ofncandidates;final_shotsre-evaluates five candidates (#399). - The ask/tell bridge in
polypus-optimizers: theAskTelltrait, withAskTellError, andAlgorithmExternalwithAlgorithmExternalArgs, which run any optimizer that implements it against anEvaluationOracle, one oracle batch perask(#399). polypus.Rotosolve(sweeps=10, reevaluate_every=5, tolerance=0.01, patience=2, seed=None), accepted bytrainandqml.train: the Rotosolve of Ostaszewski, Grant and Benedetti (Quantum, 2021), with the value reuse of the NFT method of Nakanishi, Fujii and Todo (Phys. Rev. Research, 2020). When every trainable parameter is the angle of exactly one single-Pauli rotation (any angle ofu,u2oru3included, which arerz·ry·rz, and in a Qiskit circuit the angle θ ofr) and the cost is an average over the shots, the fitness is a sinusoid of each parameter, and Rotosolve moves one parameter at a time to its maximum, in closed form. Each step is one batch of two circuits, plus the current parameters on the first step and everyreevaluate_everysteps, and after the last step the parameters it reached are measured alone;best_paramsis the best of the points measured. The run stops afterpatiencesweeps that improve the best by less thantolerance, or aftersweepssweeps.trainandqml.traincheck the circuit before anything runs (apolypus.Circuitor a Qiskit circuit; inqml.trainthe ansatz only) and raiseValueErrornaming the first gate or parameter that does not qualify;qml.trainalso rejects apolypus.SampleCost. Aninitial_pointis the first point measured. A seeded run reproduces on the same platform only, as with CMA-ES. Invalid settings raiseValueErrorbefore any circuit runs (#398).- Rotosolve in training runs (Rust,
polypus-orchestration):Method::RotosolvewithRotosolveConfig. The CUNQA walltime warning countssweeps × dimensionssteps and the final point as one more;final_shotsre-evaluatesbest_paramsalone (#398). - Rotosolve in
polypus-optimizers:AlgorithmRotosolveandAlgorithmRotosolveArgs, with aninitial_pointlike every optimizer; and inpolypus-circuit,ParameterizedCircuit::check_single_frequencywithSingleFrequencyErrorandAngleForm, which say whether a circuit qualifies;tests/python/test_rotosolve.pychecks that it and the Python check of a Qiskit circuit take the same angles and gates (#398). callbackintrain,qml.trainandqml.Model.fit(keyword-only): called once per iteration of the optimizer with a read-onlypolypus.TrainProgress(iteration,best_fitness,best_params,evaluations), so a run can report its progress, write checkpoints or stop on a criterion of its own. ReturningTruestops the run, which returns theTrainResultit has reached (converged=False; thefinal_shotsbatch is still sent);NoneorFalsego on, and any other value raisesTypeError. An exception in the callback propagates as itself, with no result. Ctrl+C keeps working as before, and a seeded run with a callback that never stops returns the same result as without one. Acallbackthat is not callable raisesTypeErrorbefore anything runs (#500).- Watching a run in Rust:
IterationObserver,IterationReportandOptimizer::optimize_observed(withoptimizenow its default, an observer that never stops), andAlgorithmDifferentialEvolution::optimize_with_strategy_observed(polypus-optimizers);TrainObserver,TrainProgress,TrainFlow::observeranddispatch_optimizer_observed, which counts the evaluations (polypus-orchestration). Adam, SPSA and Rotosolve now measure the point their last step reached inside their last iteration, with the same oracle calls and outcome (#500). final_shotsintrainandqml.train(keyword-only inqml.train): once the optimizer has stopped, its best candidates are re-evaluated in one more batch with that many shots per circuit,best_paramsand, for DE, PSO and CMA-ES, the four best other distinct candidates they scored. The newTrainResult.final_paramsis the one with the highest value andfinal_fitnessthat value; both areNonewithout it. This reduces the winner's curse ofbest_fitness, the best of many noisy estimates:final_fitnessis a fresh estimate, without bias whenbest_paramsis re-evaluated alone, and slightly optimistic still as the highest of five.best_fitnesskeeps its meaning:best_params,best_fitnessandfitness_historyare the optimizer's, and a seeded run sends the same batches with and withoutfinal_shots. The final batch has shot noise of its own (#411), so it does not repeat the training's counts for a candidate.best_paramsandbest_fitnessare logged before it, and as a warning if it fails. A value that is not an integer>= 1raisesValueErrorbefore anything runs. The batch is not part of the CUNQA walltime projection (#397).initial_pointandfinal_shotsin a native model'sModel.fit(keyword-only), withtrain's checks: a model read back withpolypus.qml.loadkeeps training from itsparams, and the final re-evaluation scores every training sample, also withbatch_size;final_shotswithexact=Trueis apolypus.ConfigurationError.fitnow checks the optimizer's configuration before any backend exists, astraindoes (#498).Model.circuit(x, params=None)andTrainedModel.circuit(x)return the circuit a native model runs for one sample as apolypus.Circuit, measured in the readout's basis; withoutparamsthe trainable angles stay free, namedtheta_0,theta_1, ... (#497).- The final batch in Rust:
EvaluationOracle::evaluate_batch_with_shots(polypus-optimizers), a provided method thatVqcOracleandQmlOracleimplement by putting the shots in every task;TrainFlow::final_shots,TrainOutcome,FinalEvaluationandMethod::final_candidates(polypus-orchestration) (#397). polypus.SPSA(max_iters=300, resamplings=1, perturbation=0.1, target_step=0.63, alpha=0.602, gamma=0.101, eval_interval=20, seed=None), accepted bytrainandqml.train: Spall's simultaneous perturbation stochastic approximation (1992), with his gainsa/k^alphaandc/k^gammaand practical exponents (1998). It estimates the gradient from two circuits per random perturbation whatever the number of parameters, so it suits many parameters and few QPUs. A calibration batch of 50 circuits around the starting point sets the gain so that, withresamplings=1, the first step moves each parameter by abouttarget_step, as Qiskit'sSPSA.calibratedoes; with more perturbations the first step is usually shorter. Each iteration is one batch of2·resamplingscircuits, soresamplingsfills more QPUs and averages that many estimates; the parameters are measured in the same batch on the first iteration and everyeval_intervaliterations, and after the last step one circuit measures the parameters it reached, so every step is measured;best_paramsis the best of them. The run makesmax_itersiterations and reportsconverged=False. Aninitial_pointis the centre of the calibration and the first point measured. A seeded run reproduces on the same platform only, as with CMA-ES. Invalid settings raiseValueErrorbefore any circuit runs. See the training guide for when to prefer it and its sensitivity totarget_stepandperturbation(#396).- SPSA in training runs (Rust,
polypus-orchestration):Method::SpsawithSpsaConfig. The CUNQA walltime warning leaves the calibration batch out of the timing and adds its circuits at the first iteration's pace, and counts the final parameters as one more iteration (#396). - SPSA in
polypus-optimizers:AlgorithmSPSAandAlgorithmSPSAArgs, with aninitial_pointlike every optimizer (#396). polypus.Adam(max_iters=100, learning_rate=0.1, beta1=0.9, beta2=0.999, epsilon=1e-8, bounds=(-math.pi, math.pi), tolerance=0.01, patience=20, finite_difference_step=0.2, rule="adam", seed=None), accepted bytrainandqml.train: gradient ascent, built on Kevin Pérez González's Adam (#394). Each iteration is one batch of2·dimensions + 1circuits, the current parameters and the central finite difference around them, so no QPU waits on a one-circuit batch, and one step. After the last step one circuit measures the parameters it reached, so every step is measured, andbest_paramsis the best of the parameters measured.max_itersandpatienceare at least 1.rule="adam"is Kingma and Ba's Adam, whose step does not depend on the scale of the cost;rule="momentum"is Polyak's heavy-ball momentum, whose learning rate does. A seeded run over a backend whose results do not depend on the platform reproduces on every platform (C-7). Invalid settings, an unknownruleincluded, raiseValueErrorbefore any circuit runs. See the training guide for the finite-difference step and for starting from a global search (#395).- Adam in training runs (Rust,
polypus-orchestration):Method::AdamwithAdamConfig. A factory now builds the run'sOracles(evaluation, and an exact gradient when it has one); Adam uses the exact gradient or a finite difference of the evaluation, and the CUNQA walltime warning counts one batch per iteration, plus the call to an exact gradient, and the final parameters as one more iteration (#394, #395). - Adam in
polypus-optimizers:AlgorithmAdam,AlgorithmAdamArgsandAdamRule, driven by a newGradientOraclecontract (the fitness gradient, uphill), with the same fitness-stagnation stop as DE and CMA-ES. A gradient of the wrong length, or with a non-finite component (the newOptimizerError::NonFiniteGradient), is an error.FiniteDifferenceGradientturns anyEvaluationOracleinto aGradientOracleby central differences, in one batch per gradient, and throughGradientOracle::value_and_gradientscores the parameters in the same batch (#394, #395). polypus.backend_compatibility(circuit, *, resources=False)lists, for each backend, why it would reject a circuit, without running it (#218). It also reports"cunqa"and"qmio"next to"aer"and"polypus"(#254). The CUNQA entry prepares the circuit as a run does and converts it with CUNQA's own converter, without raising QPUs; the QMIO entry reports a build without theqmiofeature, a Qiskit circuit and a program that is not a terminal-measurement circuit. The keyword-onlyresources=Truealso checks the native qubit ceiling and memory budget, with the message of the error the run raises.- The QML oracle (
QmlOracle, Rust) trains a nativepolypus-qmlproblem as well as Qiskit circuits (QmlSource), sampled or exact, with optional per-call minibatches (MinibatchConfig,evaluate_full) and, for the native source, the exact parameter-shift gradient, whichQmlOracleFactoryhands to Adam through the run'sOracles. Without a minibatch the gradient also returns the parameters' fitness from its own batch (GradientOracle::value_and_gradient), so an Adam iteration on a native model is one call. Both sources share the candidate windows. With a minibatch theOraclesalso carry a full-dataset view (Oracles::full_evaluation): Adam scores its parameters on it and takes only the gradient from the minibatch, and the other optimizers'best_fitnessis re-scored on it at the end. NativeStatevectorBackend::run_circuits_exact(Rust): the exact basis-state probabilities of each circuit, keyed like its counts, with no sampling and the same memory budget and windows asrun_circuits. Only for a full-register read-out.polypus-qml, a pure-Rust crate for quantum machine learning: validated datasets with deterministic splits and feature scaling; layered variational models (angle, amplitude, IQP and basis encoders, a hardware-efficient ansatz, QCNN convolution and pooling); Pauli readout with sign, threshold, argmax or raw decisions; squared-error, binary and categorical cross-entropy and hinge losses, and an unsupervisedExpectationloss that maximises the readout itself (no labels). It buildspolypus-circuitcircuits and turns measurement counts into a fitness, and into an exact parameter-shift gradient that stays exact when convolution and pooling reuse a parameter across gates, but never runs them. ATrainedModel(model plus trained parameters) saves as versioned JSON under theserdefeature. Python reaches it throughpolypus.qml.Model.polypus.CMAES(generations=100, population_size=None, sigma0=math.pi / 2, tolerance=0.01, patience=20, restarts=0, seed=None), accepted bytrainandqml.train: Hansen's (μ/μ_w, λ)-CMA-ES for periodic parameters, with optional IPOP restarts that double the population. In Rust it isAlgorithmCmaEs, withAlgorithmCmaEsArgsandCmaEsBatchSchedule, inpolypus-optimizers, with its own symmetric eigensolver (no new dependency). A seeded run reproduces on the same platform only. With restarts, the CUNQA walltime warning assumes a restart after every generation. The spread of each angle is capped atmax(sigma0, π/2), so the step size cannot grow past the 2π period and stall the run (#382). See the training guide for when to prefer it over DE.- CUNQA run-flow tests against a fake CUNQA SDK (
qraise,run,gather,qdrop, C-3 counts, C-7 per-QPU seeds), and an opt-in test for a real CUNQA family,POLYPUS_CUNQA_REAL=1 pytest tests/python/test_cunqa_real.py(#357). - OpenQASM 3 profile:
Circuit.from_qasm3,to_qasm3,param_names; the importer records the declared classical width. walltimekwarg for the SLURM walltime of CUNQA virtual QPUs.polypus.__version__, PEP 561 typing stubs andpy.typed.qaoa_params_to_dicthelper, with the real QAOA parameter order documented.- Angle expressions from
polypus.Paramin Python (2 * Param(0),polypus.sin,pi, ...), stored as circuit expressions. Circuit.clbits_width: the classical width an imported program declares.- A warning when training on CUNQA is projected to outlive the walltime.
- Native circuit drawings:
Circuit.draw()(Unicode or ASCII text, or SVG),print(circuit)and SVG display in Jupyter;draw_text/draw_svgandDisplayin Rust. No new dependencies. - Adaptive Differential Evolution:
polypus.DE(strategy="shade")(SHADE) andstrategy="lshade"(L-SHADE, whose population shrinks linearly towards 4). For"lshade",generationssets the evaluation budget,population_size × (generations + 1)as for the classic DE, and the run spends it in more, smaller generations: more sequential rounds on several QPUs, where"shade"suits better. The default,strategy="rand1bin", is the classic DE, unchanged; an unknown name raisesValueError. In Rust,DeStrategy(withmax_generations) andAlgorithmDifferentialEvolution::optimize_with_strategy. initial_pointintrainandqml.train(keyword-only inqml.train) starts the search from a given point, such as an earlier run'sbest_params:dimensionsfinite numbers as a list, tuple or NumPy array, otherwiseValueErrorbefore anything runs. DE (everystrategy) evaluates it, wrapped into[0, 2π), as the first member of its initial population; PSO as its first particle, which must lie withinbounds; QNG starts from it and Adam evaluates it first; CMA-ES centres its first run on it and keeps itssigma0, so a refinement wants a smaller one. Without it every optimizer behaves as before, seeded runs included (#395). In Rust, each optimizer'scheck_preconditionschecks its configuration and then the point without running anything, andpolypus_orchestration::Method::check_preconditionscalls the one the method names.polypus.ConfigurationError, apolypus.PolypusErrorthat is also aValueError. Every argument and configuration check ofrun_quantum_circuit,train,qml.train,qml.predictand a native model'sModel.fit,TrainedModel.predictandTrainedModel.runraises it (an unknowninfrastructure, a badwalltime, an optimizer setting,optionsonlocal/cunqa, a loss without labels, …), as dopolypus.DE(strategy=...),polypus.Adam(rule=...)and the argument checks of thepolypus.ask_telladapters, soexcept polypus.PolypusErrorcatches them andexcept ValueErrorstill does (#418, #507). Building a native model (qml.Encoder,qml.Ansatz,qml.Readout,qml.Dataset,qml.load) raises a plainValueError, as building apolypus.Circuitdoes.polypus.SPSA(stability_constant=0.0): Spall's stability constantAof the step gaina/(k + A)^alpha, finite and>= 0. The calibration keeps the first step attarget_stepwhateverA, so a largerAmakes the early steps shrink more slowly;0keeps the previous gains, and seeded runs are unchanged. It comes afterseedin the positional order. Rust:AlgorithmSPSAArgs::stability_constantandpolypus_orchestration::SpsaConfig::stability_constant(#467).Circuit.compose(other, qubits=None)/ParameterizedCircuit::compose(andtry_compose) place a circuit onto chosen qubits of another: qubitiofotherlands onqubits[i], free parameters are shared by index, and classical bits are not renumbered. Every instruction is checked as its gate method checks it (contract C-4) before any is appended, so a failed call leaves the circuit unchanged; the errors are the newCircuitError::InvalidQubitMapandCircuitError::ConflictingParamNames(ValueErrorin Python) and those of the gate methods.shor_order_findingtemplate: Beauregard's order-finding circuit for Shor's algorithm, moduli up to 24 bits.polypus.circuits.templates.shor_order_finding(a, modulus, counting_qubits=None)/polypus_circuit::templates::shor_order_findingreturns the circuit (2n counting qubits by default, no measurements) whose counting register estimates the order ofamodulomodulus;MAX_SHOR_MODULUS_BITSis the 24-bit limit, the largest circuit the OpenQASM importers read back. The arithmetic blocks it is built from are public in Rust undertemplates::arithmetic:phase_adder,modular_phase_adder,controlled_modular_multiplierandcontrolled_modular_multiplication. Their invalid arguments are the newCircuitError::InvalidTemplateArgument(ValueErrorin Python).qftandshor_order_findingbuild without holding the GIL.polypus.shor.factor: Shor's algorithm end to end, from the classical shortcuts to the order-finding circuit.factor(n, infrastructure=..., shots=1024, a=None, counting_qubits=None, max_attempts=10, seed=None, **run_kwargs)splits a compositenbelow2**24on any backend and returns aShorResult(factors, method, base, order, attempts, peak_share, uniform_peak_share, counts).method="quantum"says where the order was read, not that the circuit worked: to judge the circuit, comparepeak_share, the share of the shots on the peaks of the order (all but the one at 0), with the level of an ideal circuit and withuniform_peak_share, the share uniformly random outcomes would put there.order_from_measurementandfactors_from_order, its classical post-processing, are public in the same module.
Changed¶
polypus-quantumrequiresqiskit>=2.0,<3andqiskit-aer>=0.17,<0.18, the releases the execution seam is tested on (contract C-10); 0.7.2 set no upper bound (#362).- Argument and configuration errors are now
polypus.ConfigurationError, apolypus.PolypusError, so anexcept polypus.PolypusErrorplaced before anexcept ValueErrornow catches them (#418). - BREAKING: a seed means the same across the calls of one run on every
backend: each call gets its own sampling stream. Aer, CUNQA and the
subprocess bridge received the run's seed on every call, so batch slot
igot the same random numbers in every generation; they now receive it on the first call and a seed derived from it and the call's index on the next ones, as the native backend already did per circuit. Arun_quantum_circuitthat is one call is unchanged; seededtrain,qml.trainand multi-call runs on those backends change. Contract C-7 states it, anddocs/backends.mdsays what a third-party backend must do (#411). - BREAKING:
polypus.Qubo,polypus.Isingand a Python cost function sum each candidate's count-weighted cost in ascending bitstring order instead ofHashMapiteration order, which differs between processes, and the cost function is called in that order. The cost sums no longer depend on the process, so a seeded nativetrainreplays bit for bit in another process (contract C-7); fitness values of costs with inexact sums can move in the last bit (#401). - BREAKING:
polypus.DEtreats the parameters as angles: every strategy takes a difference between two members as the shorter arc, in(−π, π], so an optimum near 0 converges as well as one at π."rand1bin"always takes one coordinate of a trial from the mutant, so no trial is a plain copy of its parent. Seeded DE results change (#410). - BREAKING (Rust):
AlgorithmDifferentialEvolutionArgsandpolypus_orchestration::DeConfighave the fieldsmutation_factorandcrossover_rate(#410). - BREAKING (Rust):
polypus_orchestration::Methodhas a new variant,External, so an exhaustivematchon it outside its crate must handle it (#399). - BREAKING (Rust):
polypus_orchestration::Methodhas a new variant,Rotosolve, so an exhaustivematchon it outside the crate must handle it (#398). - BREAKING (Rust): an
Optimizerimplemented outsidepolypus-optimizersnow implementsoptimize_observed, which shows anIterationObservereach iteration, instead ofoptimize, now its default with an observer that never stops (#500). - BREAKING (Rust):
polypus_orchestration::TrainFlowhas anobserverfield (Nonekeeps the previous behaviour) (#500). - BREAKING: with
infrastructure="qmio"or a registered backend ("subprocess"or a third-party one), anoise_modelor asim_methodother than"automatic"raisesValueErrorinstead of being ignored, and so does abackendother than"aer"on a registered backend. This applies torun_quantum_circuit,train,qml.trainandqml.predict(#334). - BREAKING: the native backend (
backend="polypus","statevector"or"polypus_statevector") raisesValueErrorfor asim_methodother than"automatic"instead of ignoring it, inrun_quantum_circuitandtrain(#334). - BREAKING (Rust):
polypus_backend_conformance::circuits::as_qasm2returns aResultinstead of panicking on an unexportable circuit (#350). - BREAKING (Rust): registry options carry a string or a list of strings:
BackendBuildContext::optionis removed andoptionsisHashMap<String, OptionValue>; read them withoption_stroroption_list. The subprocess backend'scommandtakes a list as the exact argv; Python callers passing strings need no change (#293, ADR 0005). - BREAKING: the native backend derives each circuit's seed from the base
seed and the circuit's index with SplitMix64 instead of
seed + index, so neighbouring seeds no longer share streams shifted by one circuit (circuitkof seedsequalled circuitk-1of seeds+1). The same seed and batch still reproduce bit-for-bit (C-7), but counts andbackend="polypus"training trajectories for a fixed seed differ from earlier releases (#348). import polypusno longer calibrates the gate-parallel threshold or writes the cache: the first native statevector run of a process does it (polypus.statevector, orrun_quantum_circuit/trainwithbackend="polypus"). The cache,POLYPUS_NO_AUTOCALIBRATEand the SLURM/OpenMPI rank check are unchanged (#351).- BREAKING: Python 3.9 (end of life) is no longer supported;
requires-pythonis>=3.10and wheels are built for CPython 3.10–3.13. Every wheel is installed and smoke-tested on its platform before it is published (#360). - BREAKING (Rust):
ParameterizedCircuitandConcreteCircuitfields are private; read them withnum_qubits(),num_params(),gates()andConcreteCircuit::into_gates().ConcreteCircuit::newvalidates its gates like the builder and panics on invalid ones;try_newandtry_with_gates(for transpilers) return the error instead (#349). - BREAKING (Rust):
GateInstruction,CircuitError,BackendErrorandSimErrorare#[non_exhaustive]; amatchon them needs a wildcard arm. The simulator reports an instruction it does not know asSimError::UnsupportedInstruction(#349). - BREAKING: the declared classical width is kept through circuit binding
and export (
fix(circuit)!). - BREAKING: migrated to the
rand0.10 API; seeded streams may differ from earlier releases, and the publicpolypus-physicssamplers (EnergySpectrum::sample_energy_mev,BeamSource::sample_state,DivergentBeam/ParallelBeam::sample,sample_step_length,MonteCarloEngine::run*,interactions::*) take rand 0.10'srand::Rng(#273). - BREAKING: an exception Qiskit or Aer raises during a run is raised as
polypus.BackendError, or aspolypus.EvaluationErrorwhile composing or binding circuits, with the original as__cause__;except QiskitErrorno longer catches it. In Rust,polypus_evaluation::EvaluationErrorhas the variantsQiskitandQml, andPythoncarries aDisplaySafePyErr(#218). - Native, Aer and CUNQA backends lower gates outside the target's basis before running; the Aer lowering of a repeated OpenQASM program is cached.
- BREAKING:
templates::qftandqft_with_optionsreturn aResult: aboveMAX_QFT_QUBITS(2827) qubits, whose gates would exceed what the OpenQASM importers read back, they fail withCircuitError::TemplateTooLarge(ValueErrorin Python) instead of exhausting memory (#356). - BREAKING: QMIO has no default endpoint; set
ZMQ_SERVERor passoptions={"endpoint": ...}. The transport threat model is documented. - BREAKING: QMIO reports a Qiskit circuit as
UnsupportedCircuitinstead of a genericQmioError. - BREAKING:
run_qc_in_qpu,run_qcs_in_qpuandrun_worker_qpu.pyare removed; they could not run against any supported CUNQA version. - The QIR export declares the circuit's classical width in
required_num_results, as the OpenQASM exports do. - BREAKING:
expectation_valueandexpectation_valuesraiseValueErrorfor counts that sum to zero instead of returning0.0. - BREAKING (Rust): Rust no longer sends the
backendandidkwargs thatrun_qcsnever read (contract C-1):BackendConfig::LocalandBackendConfig::Cunqahave nobackendfield, andLocalBackend::newandCunqaBackend::newno longer take one (#230). - The QML candidate window also follows the backend's concurrency, within the memory bound.
- BREAKING (Rust):
polypus_orchestration::DeConfighas astrategyfield;DeStrategy::Rand1Binkeeps the previous behaviour. trainandqml.traincheck the optimizer's configuration (a DEpopulation_sizebelow 4, empty PSO or QNGbounds, an invalid CMA-ESsigma0, ...) before any backend or CUNQA allocation exists, and beforeinitial_point, as the optimizer does. TheseValueErrors used to come once the backend existed (#395).- BREAKING (Rust):
AlgorithmDifferentialEvolutionArgs,AlgorithmPSOArgs,AlgorithmQNGArgsandAlgorithmCmaEsArgshave aninitial_pointfield,polypus_orchestration::dispatch_optimizertakesinitial_pointas its last argument andTrainFlowhas aninitial_pointfield;Nonekeeps the previous behaviour (#395). - BREAKING (Rust): the
polypuscrate has no default features, so it no longer enableslog/max_level_infofor every dependent; choose a level withinfo-logsordebug-logs. The wheel is built withdebug-logs, soinit_logger(level="debug")shows the optimizers' progress without a rebuild. The log-level aliases in.cargo/config.tomlare removed (#414). - BREAKING (Rust):
polypus_orchestration::OracleFactory::buildreturnsOracles; a factory with only an evaluation oracle returns it.into().dispatch_optimizertakesimpl Into<Oracles>, so a boxed oracle still works, andMethodhas anAdamvariant. - BREAKING (Rust):
polypus_optimizers::OptimizerErrorhas new variants,NonFiniteGradient(#394),InvalidCandidateandExternalOptimizer(#399), and is#[non_exhaustive]; amatchon it outside its crate needs a wildcard arm, and later variants are not breaking. - BREAKING (Rust):
polypus_orchestration::Methodhas aSpsavariant, so an exhaustivematchon it needs an arm for it (#396). - BREAKING (Rust):
polypus_orchestration::TrainFlowhas afinal_shotsfield (Nonekeeps the previous behaviour), and itsFlow::OutputisTrainOutcome, whoseoptimizationfield is theOptimizationOutcomeit returned before (#397). rust-toolchain.tomlpins the Rust that CI and the release builds use (1.99.1), and that rustup selects in a checkout; a new Rust release can no longer turn CI red under-D warnings. The MSRV stays 1.85, and the sdist does not include the file. Fuzzing and Miri use a dated nightly, and the docs, release and tutorial-sync jobs have a timeout (#415).- BREAKING:
polypus.DE, with everystrategy, andpolypus.CMAESrefusepatience=0withpolypus.ConfigurationErrorwhentrainstarts, aspolypus.Adamandpolypus.Rotosolvealready did: it compared a generation's best fitness with itself, so anytolerance > 0ended the run at once (#467). - A
final_shots(train,qml.train), amax_evaluations(polypus.External) or an adapter'sdimensionsorbatch_size(polypus.ask_tell) that is not an integer, such as4096.0,Trueor astr, raisesTypeErrorinstead ofValueError, asshotsand every other integer argument do. An integer below 1 still raisespolypus.ConfigurationError(#467). repr(TrainResult)showsfinal_paramsafterbest_paramswhen the run hadfinal_shots(#467).- BREAKING (Rust):
polypus_orchestration::Methodis#[non_exhaustive]: amatchon it outside its crate needs a wildcard arm, and a new optimizer is no longer a breaking change (#467). - With
polypus.Externalon CUNQA, the walltime warning times the first batch until the second starts, so the library's own time intell()and the nextask()is in the projection; it left that time out, which for a model-based library can be much of the run. The warning comes when the second batch starts, and a run of one batch gets none (#467). AlgorithmSPSAArgsandpolypus_orchestration::SpsaConfighave astability_constantfield (#467).
Deprecated¶
- Rust:
ConcreteCircuit::to_qasm2andto_qir, which panic on circuits they cannot export; usetry_to_qasm2and the newtry_to_qir. No internal caller uses the panicking exports any more (#350).
Fixed¶
backend="aer"reads a circuit without measurements on the full register (num_qubits-wide keys, C-3), as the native backend does, instead of raisingQiskitError(#218).- The
polypus_pythonhelpers no longer set their logger to DEBUG or write log files to the working directory;serialize_quantum_circuitwrites to a private per-user temporary directory (ordirectory=) instead of<cwd>/temp, and the helpers validate run ids as the Rust entry points do (C-9, #219). - With
infrastructure="subprocess", a worker started from a short-lived thread (a pool worker or athreading.Thread) is no longer killed when that thread exits (#220). - The native backend refuses a measured circuit whose classical width exceeds
its counts key (
creg c[65536]) withpolypus.NativeCircuitErrorinstead of panicking (#346). - Sampling shots no longer builds a
2^ncumulative table next to the statevector, memory the budget did not count; the samples are unchanged (#215). - A process waiting for the calibration cache lock behind other writers no longer writes without it after a fixed 5 s and loses an entry: only a lock with no write for the timeout counts as stale (#281).
- A missing optional library is logged with its own message instead of the generic Qiskit error (#256).
- With
infrastructure="subprocess", a worker that answers with a frame that is no protocol message (an unknownop, a field of the wrong type, a payload that is not JSON) fails the call at once with a protocol error, and the worker is killed. The bridge waited for the live worker to exit, so the call hung forever, pastrecv_timeout_ms(#492). trainandqml.trainconvertexpectation_functionbefore creating the backend, so an invalid one no longer requests a CUNQA allocation (qraise) before failing; the optimizer configuration was already checked first.qml.trainrejectsinfrastructure="qmio"before anything runs, likeqml.predict. The stubs typeoptionsas adictofstrorlist/tupleofstrvalues, which the runtime accepts, so mypy acceptsoptions={"command": [...]}(#418).- Runs on the local Aer backend or on CUNQA from several threads at once no
longer panic with
Already mutably borrowed: PyBorrowErroron Qiskit 2.0. The circuit lowering shares Qiskit's session equivalence library between threads, and Qiskit 2.0'sBasisTranslatorcannot share it; Polypus now lowers one circuit at a time, which costs no parallelism since the passes hold the GIL (#468). - The examples run as shipped.
polypus_cunqa_basic.pypassedinfraestructure=(aTypeError) and sent its CUNQA steps to"qmio", the teleportation examples called.values()on aRunResult,qft.pyneeded pandas andmax_cut_qaoa.pyrequired--method(it now defaults topolypus_local). The examples that need CESGA's CUNQA or QMIO are inexamples/hpc/, and a personal run script is gone. The newexamples.ymlworkflow type-checks every example against the typing stubs and runs the local ones (#406). max_cut_qaoa.pyreads every counts key with qubit 0 rightmost: the mean cut behind the approximation ratio and the plotted cut read it reversed, which showed only on graphs that are not symmetric under node reversal (from--qubits 5). The script now checks the mapping against Qiskit's key order before it trains (#445).infraestructures.pycompares Aer and the native backend on the Hamming-weight distribution, against a total-variation bound derived from the shot count, and exits with an error on a mismatch. The full 4096-outcome distribution with a fixed 0.05 threshold reported a mismatch on every run, since two samples of 8192 shots differ by about 0.23 (#446).- The README quickstart runs on the native backend (
backend="polypus"), so it no longer loads Qiskit Aer, which failed to import on thepython:3.10-slimtopython:3.12-slimimages with Qiskit 2.6.0 (cannot allocate memory in static TLS block; fixed in Qiskit 2.6.1). The running guide has a new Troubleshooting section for the error (#392). - The
polypus-physicstests cover thePOLYPUS_ENDF_DATA_DIRoverride without setting the variable, which raced the tests that read it and cache what they read, and write their files to per-process scratch directories instead of fixed paths in the temp directory. The crate no longer containsunsafe(#420). - With
infrastructure="cunqa", a circuit without measurements is read out on the full quantum register (num_qubits-wide keys, contract C-3) instead of failing with CUNQA'skey 'counts' not found(#253), and a circuit with several classical registers gets one flat bitstring key instead of CUNQA's space-separated one (#304). Checked on a real CUNQA 3.0.0 family; the opt-intest_cunqa_real.pynow honoursPOLYPUS_CUNQA_PATHwhen deciding to skip. - With
infrastructure="cunqa", a shot split that is uneven across the QPUs (e.g. 10 shots on 3 QPUs) gives every replica its own QPU and seed: the calls per batch size restarted at QPU 0 and the base seed, so two replicas shared both and one QPU idled. CUNQA'srun_qcstakes aqpu_offsetkwarg (C-1) (#370). - An expression id (
ExprId) is a 64-bit checksum of the expression, resolved through the circuit and trusted only after the stored nodes compare equal; with the 32-bit checksum it had, a circuit could take a foreign id for a different expression it held at the same position. A circuit stores each distinct expression once, and accepts an id of an identical expression wherever it stored it (#354). - The OpenQASM 2.0 export renames a gate declaration named
qorc(c_1), which clashed with the registers it declares and made Qiskit'sqasm2.loadsreject the program; its callers are printed with the new name (#352). - BREAKING (Rust): the native simulator rejects a gate that names one
qubit twice (
Cx(0, 0)in a hand-builtConcreteCircuit) with the newSimError::RepeatedQubitinstead of writing out of bounds; the kernels' operand checks are nowassert!s (#342). - BREAKING (Rust): a measurement's classical bit index is bounded instead
of overflowing:
try_pushrejects acbitfromMAX_REGISTER_BITSup with the newCircuitError::ClbitOutOfRange, andpolypus_sim::sample_projectedreturns aResult, withSimError::ClbitOutOfRangefor a bit beyond the counts key (#345). - BREAKING (Rust):
Statevector::expectation_zreturnsResult<f64, SimError>and rejects a qubit outside the register instead of returning a wrong value or overflowing; a repeated qubit cancels (Z·Z = I). An out-of-rangeparallel_thresholdin the calibration cache (e.g.0) is ignored as a cache miss (#353). - OpenQASM 2.0 export keeps angles at full round-trip precision.
- With
infrastructure="cunqa", a non-Aerbackendor anoise_modelraisesValueErrorinstead of being silently ignored. - A Qiskit circuit with free parameters is rejected before any backend, and
backend_compatibilityreports it. - Backends report circuits OpenQASM 2.0 cannot express instead of panicking.
- QMIO: reply bitstrings are validated and malformed
QMIO_*tuning variables are rejected. - QMIO: the
QmioBackend,run_quantum_circuit,trainandqml.traindocs state that the endpoint must be trusted, since the 64 MiB reply cap is checked only after the reply is received and does not bound memory (#78). - Subprocess backend bounds the worker frame length.
- The OpenQASM 2.0 importer enforces the OpenQASM 3 importer's size budgets (source, tokens, declarations, instructions after broadcasting, barrier operands, expression nodes) and no longer tokenizes the whole source up front: a few hundred bytes could take gigabytes (#343).
- The OpenQASM 3 importer bounds the qubits all barriers list: a full-register
barrier q;counted as one instruction however largeqwas (#344). - The OpenQASM importers normalise the instructions in place instead of
copying them; QIR bitcode export stops
llvm-asafter 120 s and always reaps it (#356). - BREAKING: CUNQA receives
cores_per_qpuunder the name CUNQA 2.4 and later expect; CUNQA 2.3 is no longer supported (supported range>=2.4,<4, #204). - Python errors and OS-entropy failures surface as typed errors, not panics.
- Memory budget honours
K/M/Gsuffixes and detects the cgroup/RAM limit. - CI runs every push to
mainto completion: the next push cancelled it, and the release gate needs a successful push run for the commit it publishes (#403). - CI tests the whole workspace (
cargo test --workspace), so a crate added to it is tested without editing the workflow, which listed the crates by hand (#412). - CI runs tests it skipped without notice: the pinned-fixture test of the
OpenQASM 3 interop with Qiskit (contract C-10), in a leg with the Qiskit
that wrote the fixtures; the QIR checks with
llvm-as; and the conformance battery against Aer. There a missing tool fails those tests instead of skipping them, and pytest lists every skip with its reason (#407). - An oracle failure that the optimizer detects, a batch answered with the
wrong number of values or a gradient with a
NaNor an infinity, raisespolypus.EvaluationErrorinstead ofpolypus.ConfigurationError(#467). polypus.SPSArefuses aresamplingsabove 2147483647 withpolypus.ConfigurationError, so that an iteration's batch fits in 32 bits;resamplings=4294967295aborted the process when it allocated the batch (#467).- The stubs type
final_shotsandExternal'smax_evaluationsasSupportsIndex, which the runtime accepts, so mypy accepts a NumPy integer (#467). - Rust:
dispatch_optimizerchecks Adam'sfinite_difference_stepwith an exact gradient too, asMethod::check_preconditionsdoes, so the two agree whatever oracles the run has (#467). - A Python test that CI skips now fails the run unless the leg's
POLYPUS_ALLOWED_SKIPSlists it (tests/python/skip_guard.py), so a test that backs a contract cannot stop running unnoticed. The floors leg installs LLVM too, and every leg replays the seeded native trainings of the C-7 determinism baseline in a second process and compares them byte for byte (#407).
0.7.2 - 2026-09-30¶
Added¶
- Third-party backends can be registered without touching this repository; conformance battery and reference templates.
- OpenQASM 2.0 coverage: gate declarations, the rest of
qelib1.inc, angle expressions over free parameters, and named free parameters. - Supervised QML:
y_traininpolypus.qml.trainand batched inference withpolypus.qml.predict. RunResult.merged_counts;RunResult.countsis now alist[dict](C-3).QuantumBackendextracted into the pyo3-freepolypus-backendcrate.
Changed¶
- BREAKING:
CompoundResult::mass_fractionsiterates in symbol order (fix(physics)!). - Counts dicts are returned in ascending bitstring order.
Fixed¶
- Last-write-wins for repeated measurements into one classical bit.
- Calibration cache is keyed by hardware fingerprint and its writes are locked.
- Aer counts keys no longer contain per-register spaces.
0.7.1 - 2026-09-23¶
Added¶
- Gate-parallel threshold calibrated per machine at import and cached by thread count; a warning is emitted when it is uncalibrated.
polypus-physicsreads ENDF-6 data from localreference-data, never downloading it.
Fixed¶
- Planner respects backend concurrency caps and bases wave splitting on the memory limit.
QmioBackendno longer holds its socket lock across await points.CancelTokenhandle exposed fromScheduler::run.- PSO rejects non-finite bounds.
0.7.0 - 2026-09-14¶
Added¶
- Native GIL-free cost observables (QUBO/Ising) with a callback fallback.
- Optional gate fusion in the simulator (
fusion, on by default). - Statevector simulation can be interrupted mid-run.
- Polyenergetic beams, coherent scattering and ENDF-6 data in
polypus-physics. - QFT circuit template and native
swapgate. - Seeds exposed for
run_quantum_circuitandtrain(C-7).
Changed¶
- BREAKING:
statevector()returns a NumPy array (feat(bindings)!). - Core refactor: the Planner,
polypus-infrastructure,polypus-orchestrationandpolypus-evaluationcrates; the Python edge is a thin layer overScheduler/Flow. - Native backend parallelises the DE population across circuits.
Fixed¶
- Training and
run_quantum_circuitrelease the GIL and honour Ctrl+C. - Unique auto-generated run ids; validated
qml.traininputs. - Backend counts, expectation values and gate parameters are validated (C-3, C-5); out-of-range qubit indices are rejected.
- Native and Aer concurrency bounded by a memory budget.
- QMIO distinguishes a send failure from an unknown result.
0.6.0 - 2026-07-03¶
Added¶
- QMIO backend, native statevector simulator for local tests, and QIR support.
- Pure-Rust circuit crate (
polypus-circuit) with OpenQASM 2.0 import/export. polypus-optimizersextracted as a pure-Rust crate; Cargo workspace.- Structured JSON logger with a
logs/directory. polypus-physicscrate (photon interaction, geometry and voxels).
0.5.0 - 2026-06-10¶
Added¶
- Oracle abstraction and the
polypus.qmlmodule. install.shinstaller and compilation tests.
(The tag is spelled v.0.5.0.)
0.4.0 - 2026-05-22¶
Changed¶
- Python bindings split into modules; documentation rebuilt for 0.4.
0.3.0 - 2026-05-05¶
Added¶
- Quantum Natural Gradient (QNG) and Particle Swarm (PSO) optimizers.
- CUNQA 2.x support.
0.2.0 - 2025-11-04¶
Added¶
- Modular infrastructures (local, CUNQA, QMIO) and differential evolution with batch processing and shot distribution.
run_quantum_circuitfor single runs and multiple expectation values.
0.1.0 - 2025-05-26¶
Initial release.