Running circuits¶
polypus.run_quantum_circuit runs one circuit and returns its measurement counts. It accepts a polypus.Circuit, a Qiskit QuantumCircuit or an OpenQASM 2.0 string.
import polypus
bell = polypus.Circuit(2).h(0).cx(0, 1).measure_all()
result = polypus.run_quantum_circuit(bell, shots=1000, infrastructure="local", seed=7)
result.merged_counts # e.g. {'00': 507, '11': 493}
The result¶
run_quantum_circuit returns a RunResult with the same shape whatever n_qpus is:
| Field | Content |
|---|---|
counts |
list[dict[str, int]], one dict per QPU in the order the shots were split. A QPU left with no shots (when shots < n_qpus) has {}. |
merged_counts |
dict[str, int] summing all of them: the circuit's counts over every shot. |
seed |
The effective seed. None only for "qmio", which is real hardware. |
id, backend, infrastructure |
The run manifest, for logging and replay. |
Pass seed=... for reproducible shot noise on every simulated backend (native, Aer and CUNQA's simulated QPUs). Aer and CUNQA take a seed below 2**63; a larger one is a polypus.ConfigurationError. "qmio" rejects an explicit seed, and also a noise_model or a sim_method other than "automatic": both apply only to Aer.
Distributing shots across QPUs¶
With n_qpus > 1 the shots are split across QPUs and run concurrently:
result = polypus.run_quantum_circuit(
qc, shots=10_000, infrastructure="cunqa", n_qpus=10
)
len(result.counts) # 10, one counts dict per QPU
result.merged_counts # the total over all 10 000 shots
infrastructure="cunqa" needs CUNQA >=2.4,<4 on the cluster. CUNQA 2.3 is not supported: it names the qraise argument cores, not cores_per_qpu, so the reservation fails with a TypeError.
CUNQA's QPUs run Aer, so with infrastructure="cunqa" the backend must be "aer" (the default) or "AerSimulator", and noise_model is not accepted; either one raises ValueError before any QPU is requested.
With infrastructure="cunqa", three keyword arguments size the SLURM allocation. nodes and cores_per_qpu must be >= 1; a 0 raises ValueError. "local" and "qmio" ignore all three.
| Parameter | Default | Description |
|---|---|---|
nodes |
1 |
SLURM nodes to request |
cores_per_qpu |
2 |
CPU cores per QPU |
walltime |
"10:00:00" |
SLURM walltime of the QPUs, as HH:MM:SS |
walltime accepts only HH:MM:SS: hours are one or more digits (so "48:00:00" is valid), minutes and seconds are two digits below 60, and the total must be above zero. SLURM's D-HH:MM:SS form is rejected. Anything else raises ValueError before any QPU is requested. The QPUs are released when the walltime runs out, so set it above the expected duration of a long optimisation. Training logs a warning after the first generation when, at that pace, the run would outlast the walltime (see Allocation walltime); the final batch of final_shots is not counted.
result = polypus.run_quantum_circuit(
qc,
shots=10_000,
infrastructure="cunqa",
n_qpus=10,
nodes=2,
cores_per_qpu=4,
walltime="48:00:00",
)
Choosing a local backend¶
With infrastructure="local", backend="aer" (the default) runs Qiskit Aer and backend="polypus" runs the native Rust statevector simulator.
- The native backend runs terminal-measurement circuits only: it rejects
reset, a gate after a measurement andif(see ADR 0001). It cannot run a QiskitQuantumCircuit. - Aer runs all of those, but rejects gates outside its basis (such as
chor a declaredgate) unless the circuit is transpiled first. - The native backend is a noiseless statevector simulator: it rejects a
noise_modeland asim_methodother than"automatic"withValueError.
polypus.backend_compatibility returns, per backend (aer, polypus, cunqa, qmio), the reasons it would reject a circuit. An empty list means the circuit runs. It runs and connects to nothing. By default it is structural; with resources=True it also checks the native backend's qubit ceiling and memory budget.
report = polypus.backend_compatibility(qc)
# e.g. {"aer": [], "polypus": ["native backend could not parse OpenQASM 2.0: ... 'reset' is not supported ..."], ...}
backend = "polypus" if not report["polypus"] else "aer"
result = polypus.run_quantum_circuit(
qc, shots=1000, infrastructure="local", backend=backend
)
A circuit without measurements is read out on all its qubits by both backends.
Typed targets¶
Instead of the infrastructure/backend strings and their provider arguments, target= takes one object that says where the run goes. Each class checks its own fields when it is built, except sim_method, which Aer checks when the run starts.
| Target | Same as |
|---|---|
polypus.Aer(sim_method="automatic", noise_model=None) |
infrastructure="local", backend="aer" |
polypus.Native(fusion=None) |
infrastructure="local", backend="polypus" |
polypus.Cunqa(nodes=1, cores_per_qpu=2, walltime=None, sim_method="automatic") |
infrastructure="cunqa" |
polypus.Qmio(program_format="openqasm") |
infrastructure="qmio", backend=program_format |
polypus.Registered(name, options=None) |
infrastructure=name, options=options |
result = polypus.run_quantum_circuit(bell, shots=1000, target=polypus.Native(), seed=7)
run_quantum_circuit, train, qml.train and qml.predict accept target=. With it, passing infrastructure, noise_model, fusion, nodes, cores_per_qpu or walltime at all, or backend or sim_method with a value other than its default, raises ConfigurationError; backend="aer" and sim_method="automatic" are ignored. options= still applies: it configures Qmio (for example its endpoint) and Registered, but not both Registered(..., options=...) and options= at once. The strings remain as shorthand, and a seeded run with target= gives the same counts as the equivalent string call; RunResult.backend and infrastructure are those of the "Same as" column.
Tracing a circuit run¶
run_quantum_circuit takes the same keyword-only trace argument as train, a path (str or os.PathLike) of a new file for the run's call trace (contract C-12), and follows POLYPUS_CALL_TRACE and POLYPUS_CALL_TRACE_MAX_MB as train does, its file in the variable's directory being named after the run's effective id, RunResult.id; see Tracing the calls of a run. The header line has "flow": "run_circuit", null as method and dims, the run's id and its effective seed (null on "qmio"). The run is one batch line, with "op": "execute_replicas", n equal to 1 and the run's shots, written after one wave line per call to the backend. With n_qpus=1 that is one run_circuits call with every shot. With n_qpus > 1 the shots are split into one replica per QPU, run by run_shots_distributed calls, and each wave line lists in replicas the shots of each replica it ran; over all the waves they add up to shots.
Logging¶
Polypus's Rust core logs through Rust's log facade: progress, fallbacks, failures it recovers from. Nothing is emitted until a sink is installed, once per process, by one of two calls:
polypus.init_logger(...)writes the records with Polypus's own sink, to a file (the default) or to stdout, with its own level and format.polypus.log_to_python()hands every record to Python'slogging, so you configure Polypus's records like any library's.
Only one of the two can be installed in a process: whichever is called second is a no-op with a UserWarning. Restart the interpreter or kernel to switch.
import logging
import polypus
logging.basicConfig(format="%(asctime)s %(levelname)s %(name)s: %(message)s")
logging.getLogger("polypus").setLevel(logging.DEBUG) # optimizer progress is DEBUG
polypus.log_to_python()
Each record goes to the logger named after the Rust module that emitted it, under polypus, so logging.getLogger("polypus") controls them all:
| Rust module | Python logger |
|---|---|
polypus_optimizers::util |
polypus.optimizers.util |
polypus_sim::calibration |
polypus.sim.calibration |
polypus::bindings::run |
polypus.bindings.run |
zeromq::codec (a dependency, with the qmio feature) |
polypus.zeromq.codec |
A record's pathname and lineno are the Rust source file and line, and its message arrives already formatted, so a % in it is kept as is. It has no Python function, so funcName is None. Most records come from threads Python did not start, so threadName is the name Python gives such a thread, Dummy-<n>; on Python 3.12 and older, the threading object created for each of them is not removed when the thread ends, and threading.enumerate() keeps listing it. Rust's TRACE level is 5, below logging.DEBUG; the published wheel emits nothing below DEBUG. log_to_python() configures no handler: with none on polypus or above it, Python's defaults apply, which print warnings and errors to stderr. The Python-side helpers in polypus_python log to their own polypus_python logger.
Which levels each polypus logger lets through is read from Python when log_to_python() runs and again at the start of each call that runs Rust code on worker threads: train, run_quantum_circuit, statevector, qml.train, qml.predict, Model.fit, TrainedModel.predict and run, qml.expval, qml.jacobian, qml.vjp, qml.kernel_matrix and calibrate_parallel_threshold. That list is complete; every other call uses the levels read last. A level lowered while one of them runs, from another thread, takes effect from the next of them on; a level raised applies at once, since each record is checked again against the live logger before it is handled.
A record emitted while the interpreter cannot be reached, because it is shutting down (a run still going on a daemon thread) or in a garbage-collection pass, cannot go to Python. An ERROR or WARNING record is then written to stderr as one line, polypus: <LEVEL> <logger name>: <message>; anything less severe is dropped.
With a build that has the qmio feature (not the published wheel), closing a QMIO backend can hang while log_to_python() is installed: the close waits for threads of the QMIO client that may be waiting to log. Use init_logger with QMIO.
Errors¶
All Polypus exceptions derive from polypus.PolypusError.
- An invalid argument or configuration of
run_quantum_circuit,train,qml.train,qml.predict, or a native model'sfit,predictandrunraisespolypus.ConfigurationError, which is also aValueError: an unknowninfrastructure, a badwalltime, an optimizer setting such asDE(population_size=3), anoptionsdict on a backend that takes none.train,qml.trainandModel.fitcheck all of them, the optimizer included, before creating the backend, so on CUNQA no allocation is requested for a run that cannot start. A value of the wrong type is aTypeError. Building a circuit or a native model (polypus.Circuit,qml.Encoder,qml.Ansatz,qml.Readout,qml.Dataset,qml.load) checks each step as it is written and raises a plainValueError. - A Qiskit or Aer failure during a run raises
polypus.BackendError, with the original exception as its__cause__. - A Qiskit failure while
train,qml.trainorqml.predictprepares or binds your circuits (for example an ansatz wider than the feature map) raisespolypus.EvaluationErrorthe same way. - An exception raised by your own
expectation_functionreaches you unchanged. - A circuit too large for the memory budget raises
polypus.InsufficientMemoryErrorbefore anything is allocated. See Memory budget. - A circuit the native backend cannot run raises
polypus.NativeCircuitError. That includes a measured circuit whose classical register is wider than 64 bits (for examplecreg c[100];, ormeasure(0, 70)); usebackend="aer"for it. - Invalid circuit construction (an out-of-range qubit or classical bit, a non-finite angle) raises
ValueError.
Polypus is written not to panic. If a Rust panic does happen, it is a bug: it reaches Python as pyo3_runtime.PanicException, which derives from BaseException, so neither except Exception nor except polypus.PolypusError catches it. Please report it.
Troubleshooting¶
import qiskit_aer fails with "cannot allocate memory in static TLS block"¶
ImportError: .../qiskit_aer.libs/libgomp-<hash>.so.1.0.0: cannot allocate memory in static TLS block
Aer bundles its own OpenMP runtime, libgomp, which needs room in glibc's static TLS reserve when Python loads it. If the libraries loaded before it have filled the reserve, the import fails, and so does every run on backend="aer", the default. Polypus is not involved: import qiskit_aer alone fails the same way. Qiskit 2.6.0 is a known cause, for instance on the python:3.10-slim to python:3.12-slim images (Debian 13, glibc 2.41); Qiskit 2.6.1 fixes it (Qiskit/qiskit#17213):
pip install --upgrade "qiskit>=2.6.1"
Otherwise, run on the native simulator, backend="polypus", which does not load Aer, or enlarge the reserve before Python starts:
export GLIBC_TUNABLES=glibc.rtld.optional_static_tls=16384
The dynamic loader reads the variable when the process starts, so setting it in os.environ from Python has no effect. In a Dockerfile, set it with ENV.
Writing a backend documents the backend contract in detail.