Primitives¶
QMSamplerV2 and QMEstimatorV2 are QOP-aware adapters of Qiskit’s V2 Sampler and Estimator — same pub interface, but execution leverages input streaming, real-time parameter updates, and (for Estimator) on-device control flow.
For signatures and options fields, see the Primitives API reference.
Purpose¶
Generic cloud primitives assume parameters are bound at submission time. QOP workloads often stream parameters cycle-by-cycle via InputType (INPUT_STREAM, IO1, IO2, OPNIC). These primitives expose that capability while reusing QuAM-derived Targets for transpilation.
The traditional QMBackend.run() interface mimics Sampler-like behavior for users who prefer the classic backend API. Like backend.run, primitives respect the max_circuits backend option and will split large batches into multiple QUA programs when needed. See Backend — multi-circuit batches.
Classified measurement outcomes only¶
Only classified results (0/1 bitstrings / counts) are reliably supported today. Experiments requiring raw I & Q, kerneled shots, or other non-discriminated outputs are not yet supported. Contributors welcome.
Although QMSamplerOptions.meas_level accepts "kerneled" and "avg_kerneled" in the API, those paths are not production-ready. Use "classified" (the default) for all current workflows, including Qiskit Experiments.
QMSamplerV2¶
Shot-based measurement counts. Maps to backend run() under the hood. The returned QMSamplerJob exposes the compiled QUA programs via get_program():
from qm import generate_qua_script
sampler = QMSamplerV2(backend=backend, options=QMSamplerOptions(default_shots=256))
sampler_job = sampler.run([qc])
print(generate_qua_script(sampler_job.get_program()))
QMEstimatorV2¶
Expectation values and standard errors with optional abelian grouping of observables. Estimator observables assume classified measurement outcomes. Returns a QMEstimatorJob.
from qiskit_qm_provider import QMEstimatorV2, QMEstimatorOptions, InputType
options = QMEstimatorOptions(input_type=InputType.INPUT_STREAM)
estimator = QMEstimatorV2(backend=backend, options=options)
job = estimator.run([(circuit, observables, parameter_values)])
result = job.result()
Which qubits are measured¶
Circuits and observables are taken as ISA: observables span the full physical register, as in Qiskit (transpile the circuit, then call observable.apply_layout(circuit.layout)). The estimator measures a qubit if and only if some term of some observable in the PUB acts non-trivially on it. The set is the union over the PUB’s whole observables array, because one compiled circuit serves every observable and binding of the PUB; on the other qubits every observable is the identity, so they cannot change any expectation value.
A qubit that no gate touches is still measured if an observable acts on it.
Ancillas are treated like any other qubit:
apply_layoutpads them with identity, so they are normally not measured, but an observable that acts on one is measured faithfully.Qubits that carry gates but no observable support are not measured, which saves their basis switch and readout.
Identity terms are never measured:
<I> = 1exactly, so they contribute their coefficient with zero variance. If every term of a PUB is the identity, the PUB is not compiled or run at all.Only Pauli terms are supported.
SparseObservableprojector terms (0,1,+,-,r,l) raise aValueError; expand them first withSparseObservable.as_paulis(), at the cost of doubling the number of terms per projector.
As in Qiskit’s BackendEstimatorV2, validate_estimator_pubs keeps the circuit as given and appends the readout below. Measurements already in the circuit still run, so pass estimator circuits without final measurements: a final measure_all would collapse the state before the basis rotations (use qc.remove_final_measurements(inplace=False) first, as in the workflow examples). Their registers are still read out and streamed, but the estimator ignores them.
Per measured qubit q_j, the prepared circuit has a basis switch driven by an input __obs_j (0: none, 1: h, 2: sdg; h) followed by a measurement into bit j of a __c register. Names starting with __ are reserved for this readout: a PUB circuit with a classical register, variable or stretch named that way is rejected with a ValueError. EstimatorPlan.from_pub requires this readout (it rejects circuits without it, and observables acting on a qubit outside __c); QMEstimatorV2.run adds it through validate_estimator_pubs. A PUB whose circuit has no parameters has no parameter table and no binding loop (only the loop over its observable groups); a PUB with zero bindings is not run, and its result is empty with the PUB’s shape.
How observables reach the OPX¶
Each measured qubit gets one basis code per measurement group: 0 for Z or I, 1 for X, 2 for Y. These codes are packed 2 bits per qubit, 15 qubits per 32-bit word. For each parameter binding, the program receives one int row, [number of groups, packed words...] (ObsRow on the host). QUA unpacks a group with shifts and masks only: the word and qubit loops are unrolled when the program is built, and the group offset is 1 + group_index * words_per_group. The host’s division that places bits into words is not replayed on the OPX.
Input streams: one push per binding. A row shared by every binding is sent once.
IO1/IO2: only the used part of the row is exchanged.
Compile time (
input_type=None): the same rows are preloaded into the program.
Parameter values and fixed-point range¶
Every circuit parameter reaches the program as a QUA fixed: a signed 4.28 fixed-point number, with range [-8, 8) and resolution 2⁻²⁸ ≈ 3.7·10⁻⁹. This holds for every input_type, including compile-time preloading. Values outside this range are not supported. When a QMSamplerV2 or QMEstimatorV2 job is created, any PUB with a bound value outside the range (or a NaN or infinite value) is rejected with a ValueError that names the PUB, the parameter and the binding. Nothing is clipped or wrapped for you.
Angles in [-π, π] or [0, 2π] fit. Quantities with a larger natural scale do not, for example durations, frequencies or angles accumulated over many turns. Bind such a quantity in a rescaled unit that stays inside [-8, 8), and undo the scale in the circuit, as long as the expression stays in range (see the warning below).
Warning
The range check covers the bound values only. It does not cover expressions built from parameters. A gate argument such as rx(3 * theta), rz(theta + phi + chi) or rx(theta * phi), or a backend macro that scales an angle, is evaluated in real time, in fixed-point arithmetic, on the controller. Each value can be in range while an intermediate or final result is not: with theta = 3.0, 3 * theta = 9.0 cannot be represented in fixed, and the provider raises no error. The gate then receives a wrong value. Products of small values also lose resolution, since only 28 fractional bits remain.
Before running, check the extreme values of every parameter expression in your circuits, not just of the parameters.
When the risk is high for your use case (large dynamic ranges, long sums, products of parameters), please reach out to the maintainer first (open an issue on the GitHub repository or write to the author listed in pyproject.toml). In general, such kernels have to be written in QUA as real-time processing with explicit rescaling, rather than expressed as Qiskit parameter arithmetic. QUA’s Cast utilities (from qm.qua import Cast) are the main tools for this:
Cast.mul_fixed_by_int(x, n)andCast.mul_int_by_fixed(n, x)multiply afixedby anintwithout first converting the integer tofixed. An integer ≥ 8 cannot be afixed, so carry large integer factors asintand combine them only through these helpers. The result must still fit its output type.Cast.to_int,Cast.to_fixedandCast.to_boolconvert values between types.Cast.unsafe_cast_int,Cast.unsafe_cast_fixedandCast.unsafe_cast_boolreinterpret the raw 32 bits without conversion. Use them with integer shifts to scale by powers of two, or to carry a wider-range quantity as an integer part and a fractional part.
See the QUA reference guide in the QM documentation for the full semantics of QUA variable types, arithmetic and the Cast module.
Options at a glance¶
Option |
Sampler |
Estimator |
Meaning |
|---|---|---|---|
|
✓ |
✓ |
How parameters reach the OPX: stream, IO, QUARC-backed OPNIC (sampler only; the estimator raises |
|
✓ |
— |
Default shots when not specified in |
|
— |
✓ |
Default precision (e.g. 1/√4096) when not specified |
|
— |
✓ |
Group commuting observables (default |
|
✓ |
✓ |
Per-job overrides of backend run options ( |
|
✓ |
— |
Use |
Configure options via QMSamplerOptions or QMEstimatorOptions. Set input_type=None to bind all parameter values at compile time (suitable only when the number of distinct parameter sets is small).
Large PUB batches and max_circuits¶
On primitives, max_circuits counts PUBs, not Qiskit circuits and not parameter bindings. Each PUB is already one circuit plus its bindings (and observables for the estimator). The provider never splits a PUB across programs: every binding of that PUB stays in the same QUA loop.
When len(pubs) exceeds max_circuits, PUBs are packed into consecutive chunks of at most that many PUBs. Each chunk becomes one QUA program, queued sequentially on QOP. The returned PrimitiveResult still has one entry per input PUB in the original order.
Precedence (that job only; backend.options is not mutated):
QMSamplerOptions.run_options["max_circuits"]/QMEstimatorOptions.run_options["max_circuits"]else
backend.options.max_circuits(default30)
# Per-job override (backend default stays 30):
sampler = QMSamplerV2(
backend=backend,
options=QMSamplerOptions(run_options={"max_circuits": 1}),
)
# 12 PUBs → 12 QUA programs (one PUB each). Bindings inside a PUB are not split.
# backend.options.max_circuits is still 30
job = sampler.run([pub_0, pub_1, ..., pub_11])
# Or change the backend default for every caller (including Qiskit Experiments job splitting):
backend.set_options(max_circuits=5)
Qiskit Experiments exp.run(sampler=sampler) is a second, earlier split. It reads backend.max_circuits (and optional exp.set_experiment_options(max_circuits=N)) and hands the sampler a list of circuits. Each of those circuits becomes one PUB. Experiments never reads sampler run_options.
If both knobs are set, run_options win inside that sampler.run() / estimator.run() call:
Who sets what |
Experiments |
QUA programs from those PUBs |
|---|---|---|
Only |
5 circuits → 5 PUBs |
1 program of 5 PUBs |
Only sampler |
30 circuits → 30 PUBs (backend default) |
30 programs of 1 PUB |
Backend |
5 circuits → 5 PUBs |
5 programs of 1 PUB |
Backend |
1 circuit → 1 PUB |
1 program (the sampler cap cannot enlarge a smaller Experiments batch) |
To make Experiments submit fewer circuits per Python job and pack one PUB per QUA program, set the backend (or exp.set_experiment_options(max_circuits=N)). Use sampler run_options when you only want a tighter PUB-per-program limit without changing the shared backend.
Running on IQCC Cloud¶
When the backend is an IQCC cloud backend, QMSamplerV2.run() / QMEstimatorV2.run() return an IQCCSamplerJob / IQCCEstimatorJob. For streamed input_types, the job submits the QUA program together with an auto-generated sync hook — a small Python script that runs on the cloud side and pushes, in program order, each PUB’s parameter rows (and, for the Estimator, its packed observable rows) into the running program.
The sync hook is fully self-contained. It imports only:
from iqcc_cloud_client.runtime import get_qm_job
and drives the QM job directly. It does not require qiskit_qm_provider, numpy, or qualang_tools to be installed in the cloud runtime, so any IQCC user can run streamed primitives without extra packages. Parameter tables are serialised to plain Python data before submission and the push logic is rendered from a Jinja template; values are coerced to each parameter’s QUA type (int / fixed / bool).
Supported input_type on IQCC¶
|
IQCC support |
Cloud mechanism |
|---|---|---|
|
✓ |
|
|
✓ |
|
|
✓ |
Values bound at compile time (no sync hook); only for small parameter sets |
|
✗ |
Raises |
from qiskit_qm_provider import (
IQCCProvider,
QMSamplerV2,
QMSamplerOptions,
InputType,
add_basic_macros,
)
# 1. Grab the cloud backend by name ("arbel", or whichever quantum computer you have access to).
backend = IQCCProvider().get_backend("arbel")
# 2. IQCC does not yet ship the standard single-qubit gate macros, so add them once
# after fetching the backend. This populates x, sx, rz, sy, sydg, measure, reset,
# delay, id, and cz macros and syncs the backend target.
add_basic_macros(backend)
# 3. Streamed primitives run on any IQCC user's cloud runtime — no provider install needed cloud-side.
sampler = QMSamplerV2(backend=backend, options=QMSamplerOptions(input_type=InputType.INPUT_STREAM))
job = sampler.run([(circuit, parameter_values)])
# OPNIC over IQCC is not supported yet and raises at run():
QMSamplerV2(backend=backend, options=QMSamplerOptions(input_type=InputType.OPNIC)).run([circuit])
# NotImplementedError: OPNIC input_type is not yet supported for IQCC cloud jobs; use INPUT_STREAM or IO1/IO2.
IQCC cloud failures and run_data¶
Cloud-side failures (config validation, open_qm errors, etc.) often surface locally as a misleading KeyError on a measurement stream (for example KeyError: '__c_0') because the QUA program never reached the streaming stage.
All IQCC wrapper jobs — CloudQMJob, IQCCSamplerJob, and IQCCEstimatorJob — expose the raw IQCC execution record on job.run_data (backed by job.get_qm_job()._run_data). Typical keys:
Key |
Content |
|---|---|
|
QM / QOP log lines from the cloud runtime |
|
Python traceback when the remote script failed |
|
Timing and fridge metadata when execution completed |
When job.result() is called, the wrapper inspects run_data["stderr"] and, if it contains a Python traceback, raises IQCCCloudExecutionError with the exact cloud stderr as the exception message — instead of a local stream KeyError.
from qiskit_qm_provider.job import IQCCCloudExecutionError
try:
result = job.result()
except IQCCCloudExecutionError as exc:
print(exc) # full cloud traceback
print(job.run_data["stdout"]) # e.g. PHYSICAL CONFIG ERROR lines
You can also inspect job.run_data after submission without calling result() when debugging a failed cloud run.
Debugging generated QUA¶
Every primitive job and backend.run() exposes the compiled QUA programs via get_program() (single/default) or by iterating job.programs (all chunks). See the Jobs guide for the full accessor table (qm_jobs, get_qm_job(), get_program(), get_result_handles(), pubs, IQCC run_data, …).
Both primitive jobs also expose their execution plans on job.runtime_pubs: one SamplerPlan or EstimatorPlan (from qiskit_qm_provider.job.primitive_plan) per input PUB. An EstimatorPlan shows the measured qubits, how observables were grouped (metadata, obs_codes) and the packed rows streamed to the OPX (obs_rows, each an ObsRow).
from qm import generate_qua_script
# Non-chunked (default): use the getter
print(generate_qua_script(job.get_program()))
# Chunked: iterate all programs
for chunk_idx, prog in enumerate(job.programs):
print(f"=== QUA program {chunk_idx} ===")
print(generate_qua_script(prog))