Backend and Utilities¶
QMBackend is the central bridge object: it represents hardware to Qiskit (via a QuAM-derived Target) and translates Qiskit artifacts to QUA (via qm_qasm and quantum_circuit_to_qua).
For full signatures, see the Backend API reference.
Purpose¶
Backends serve two roles:
Represent hardware in Qiskit — macros from QuAM populate the
Target; coupling map from topology; qubit properties (T1, T2, frequencies).Translate circuits to QUA — OpenQASM 3 export + qm_qasm compilation, or Pulse schedule conversion (Qiskit 1.x legacy).
FluxTunableTransmonBackend is the reference implementation: init_macro from QuAM’s initialize_qpu, and QuAM ↔ Pulse channel mapping (get_quam_channel, get_pulse_channel).
Two execution modes¶
Submit-and-run¶
Standard Qiskit backend workflow: compile, execute, return a QMJob. Use get_program() to access the compiled QUA:
from qm import generate_qua_script
job = backend.run(qc, shots=256)
print(generate_qua_script(job.get_program()))
result = job.result()
Multi-circuit batches and max_circuits¶
When you pass a list of circuits to QMBackend.run(), the provider may build more than one QUA program and queue them sequentially on QOP. Results are still returned as a single Qiskit Result with experiments in the same order as your input list.
This behaviour also applies to QMSamplerV2 and QMEstimatorV2 — see the Primitives guide for details. It does not apply to quantum_circuit_to_qua.
Backend option max_circuits (default 30):
Value |
Effect |
|---|---|
Positive integer |
Pack at most this many circuits (or PUBs) per QUA program. Larger batches are split into consecutive chunks (e.g. 70 circuits → 30 + 30 + 10). |
|
Disable size-based splitting — always one QUA program for the full batch (unless calibrations force a split; see below). |
Set it at construction time or update it at any point before submitting a job:
# At construction time:
backend = FluxTunableTransmonBackend(machine, max_circuits=10)
# Or update after construction — default for the next backend.run() / primitive run
# that does not override max_circuits in run_options:
backend.set_options(max_circuits=10)
# Per-call override (does not mutate backend.options):
job = backend.run(circuits, max_circuits=1)
Primitive run_options["max_circuits"] is the same kind of per-job override. Qiskit Experiments still splits its own jobs from backend.max_circuits; see Primitives — large PUB batches.
Splitting rules (in priority order):
Conflicting calibrations — one circuit per QUA program (unchanged).
len(circuits) > max_circuits— consecutive groups ofmax_circuitscircuits.Otherwise — a single program holding all circuits.
Inspecting generated QUA — job.programs is always a list[Program] (length 1 when no chunking occurred, otherwise one entry per chunk):
from qm import generate_qua_script
circuits = [make_circuit(i) for i in range(100)]
job = backend.run(circuits, shots=256)
for chunk_idx, prog in enumerate(job.programs):
print(f"=== QUA program {chunk_idx} ===")
print(generate_qua_script(prog))
result = job.result() # one Result; experiment order matches `circuits`
Use a smaller max_circuits when a single packed program grows too large for QOP compilation or device limits. Use max_circuits=1 to force one circuit per QUA program.
Embed-in-QUA (hybrid)¶
Inside with program():, compile a circuit as a QUA macro and wire classical outcomes in the same program:
from qm.qua import program, save
with program() as prog:
comp = backend.quantum_circuit_to_qua(qc, param_table=my_param_table)
save(comp.outputs.state_ints["meas"], comp.outputs.streams["meas"])
QuaCircuitCompilation exposes wired handles via comp.outputs (MeasurementRegisterField per creg). See the Measurement outputs guide for the accessor contract and locality model.
Call measurement wiring immediately after quantum_circuit_to_qua in the same QUA program — not as a separate Python post-processing step.
Real-time parameters¶
Unlike typical Qiskit backends, parameters need not be bound at compile time. Use ParameterTable.from_qiskit() to map circuit parameters to real-time QUA variables (phases, amplitudes, frame rotations).
Warning: QOP rejects non-ASCII parameter names. Use ASCII names (theta, phi) — not Greek symbols — so OpenQASM 3 and QUA compilation succeed.
Table fields keep the Qiskit names. The OpenQASM 3 exporter may rename an input (gates and variables share one namespace, so a ParameterVector called x exported as an array next to the x gate becomes x_0; a name that is not an identifier, such as theta.1, is escaped). quantum_circuit_to_qua matches inputs by Qiskit object, so a renamed input still binds to its field. It raises ValueError, naming each input, when one has no binding or a binding of the wrong shape (scalar vs. array, array length): qm-qasm itself would broadcast a scalar into an array input without complaint, and fails on a missing input with an opaque Qua1GenerationPass failed.
param_table copies each binding into a new QUA variable. Pass declared tables or standalone Parameter objects in table_by_ref to alias those variables instead: the circuit uses them directly, and an assignment in the OpenQASM program updates the caller’s variable. Tables passed by reference must already be declared, and each aliased variable must have the input’s dtype (fixed for a float parameter): qm-qasm cannot alias an int variable as a float[64] input. Each circuit input must come from one argument or the other; the same exported input in both raises ValueError.
with program() as prog:
copied.declare()
aliased.declare()
backend.quantum_circuit_to_qua(qc, param_table=copied, table_by_ref=aliased)
Exporting ParameterVectors as arrays¶
The backend option export_vector_as_array (default True) exports each ParameterVector as one full-length input array[float[64], N]. It needs the full_real_time_expr Qiskit branch (its PARAMETER_VECTORS_AS_ARRAYS exporter feature) and is ignored on stock Qiskit, which exports one scalar input per used element. Turn it off with backend.set_options(export_vector_as_array=False). Tables built by ParameterTable.from_qiskit on the branch hold a vector as one array field, which binds either export.
The OpenQASM 3 exporter is internal¶
quantum_circuit_to_qua always exports through backend.qasm3_exporter, which is configured for this backend (its basis gates, angles written in terms of the OpenQASM constants pi, euler and tau, and the export_vector_as_array option). qm-qasm expects that output: circuits laid out on physical qubits and expressed in the backend’s native operations. Exporting with your own Exporter (or other options) and feeding the result to qm-qasm yourself is possible, but it is not a supported path: nothing checks that its operations, qubits or input declarations match what the compiler and your tables expect.
Utilities¶
add_basic_macros¶
Seeds standard gate macros on a QuAM machine. Flux-tunable transmon defaults tied to FluxTunableQuam — see Providers guide. Override freely for other platforms. Canonical import: from qiskit_qm_provider import add_basic_macros. Importing it from qiskit_qm_provider.backend.backend_utils is deprecated.
get_qua_script / dump_qua_script¶
Debug helpers that compile a circuit on its own and print (or write) the QUA script that would run, to inspect its pulse sequence. They compile outside any QUA program, so no ParameterTable or Parameter can be declared: pass a dict of plain Python values in param_table, and every input you leave out starts from a typed zero (0.0, 0 or False, or a list of them for an array input). A parameterized circuit therefore needs no bindings at all. Passing a table raises TypeError; to compile with real streamed parameters, call quantum_circuit_to_qua inside with program():.
print(get_qua_script(backend, tqc)) # every input starts at zero
print(get_qua_script(backend, tqc, param_table={"theta": 0.25}))
assign_struct_with_table¶
QUA macro for OPNIC struct assignment when a :class:~.ParameterTable and a Quarc QuaStructHandle share the same field layout. Call inside with program(): after:
table.declare()(or OPNICtable.initialize_in_qua()) — source parameters must have QUA variables.struct.initialize_in_qua()— destination struct must be declared in the same program.
The macro copies each table parameter’s QUA variable into the matching struct field via qm.qua.assign. Field names and sizes (scalar vs. array length) must match exactly.
from qm.qua import program
from qiskit_qm_provider.utils.quarc.struct_assign import assign_struct_with_table
with program() as prog:
policy_table.declare()
outbound_handle.initialize_in_qua()
assign_struct_with_table(outbound_handle, policy_table)
outbound_handle.send()
struct must be a Quarc QuaStructHandle from module.add_struct(...) (validated at runtime via lazy quarc import).
Custom calibrations (Qiskit 2.x)¶
Attach QUA macros to Target instructions via QMInstructionProperties:
from qiskit.circuit import Parameter as QiskitParameter, Gate
from qiskit_qm_provider import QMInstructionProperties
theta = QiskitParameter("theta")
cx_cal = Gate("cx_cal", num_qubits=2, params=[theta])
def qua_macro(theta_val):
qubit_pair = backend.get_qubit_pair((0, 1))
qubit_pair.apply("cz", amplitude_scale=theta_val)
properties = {
(0, 1): QMInstructionProperties(
duration=backend.target["cx"][(0, 1)].duration,
qua_pulse_macro=qua_macro,
)
}
backend.target.add_instruction(cx_cal, properties=properties)
backend.update_target() # mandatory — syncs qm_qasm with the Target
Whenever you modify backend.target, call update_target so both transpilation and quantum_circuit_to_qua see the same gate set.
QMInstructionProperties also exposes extra Target display data:
quam_macro/qua_pulse_macroremain the programmatic accessors.print(backend.target)(on Qiskit versions that render extra properties) shows a compactquam_macrorepr, or a callable’s qualified name rather than<function ... at 0x...>.Two-qubit QuAM macros often store
fidelityas a mapping of benchmark names (not a float). That map is available asfidelity_dict.print(backend.target)unrolls each benchmark (rb,xeb, …) as its own extra property. It is not converted into a scalarerror: the RustInstructionPropertiesused by the transpiler still only seesdurationanderror.
Barrier and store¶
Besides the QUA-backed operations above, every QM backend Target defines barrier and store as global, variable-width operations, just as it defines control flow (if_else, box, …). They have no QUA macro of their own and never appear in the qm-qasm operations mapping, because qm-qasm lowers them itself:
store(a real-time classical assignment,qc.store(var, value)) becomes a QUA assignment.barrierbecomes a QUAalignover every element of the barrier’s qubits (as given bybackend.qubit_mapping), so the operations after it start together. Only the elements mapped to those qubits are aligned: map couplers or other shared elements to the qubits they act on if a barrier should align them too.
Conditional pulse plays¶
A conditional play applies one fixed QuAM pulse when a run-time Boolean Qiskit expression is true. It lowers directly to QUA pulse.play(condition=...); it does not introduce a Qiskit if_test or an enclosing QUA branch. Build one with QuantumCircuit.conditional_play(...) (shown below) or the equivalent standalone add_conditional_play(qc, ...) function.
The construct has two deliberately separate inputs:
pulse_nameis compile-time metadata. It selects the QuAM pulse and must resolve uniquely throughqubit.get_pulse(pulse_name)on every active physical qubit.conditionis a run-timeqiskit.circuit.classical.expr.Exprwhose type must be Boolean. It is lowered through Qiskit’s typed classical-expression AST, not through a numeric QiskitParameter.
Internally this is a private provider Instruction, always wrapped in a box by conditional_play/add_conditional_play (there is no supported way to construct one directly) and exported through Qiskit’s implicit-defcal call path. The emitted OpenQASM operation name is qm_conditional_play_x180 when pulse_name is already a valid OpenQASM 3 identifier (the common case), or qm_conditional_play_minus_x90 for the "-x90"/"-y90" negated-pulse convention. A pulse label using any other character falls back to a sanitized name with a digest suffix. The one known collision is between a --prefixed label and one spelled out with minus_ (for example "-y90" and "minus_y90"): both map to qm_conditional_play_minus_y90, and register_conditional_play warns when the second one replaces the first. The pulse label is never passed as a run-time argument.
Registration and compilation¶
Register a pulse label once before transpiling. Registration resolves the label on all active qubits, installs one per-qubit Target mapping, and synchronizes the qm-qasm operation mapping. There is no need to call update_target() again after a successful registration. To register several labels, pass them in one call, e.g. backend.register_conditional_play("x180", "-y90"): all of them are resolved before any is installed (a lookup error registers none), and the operation mapping is synchronized once.
from qiskit import transpile
from qiskit.circuit import ClassicalRegister, QuantumCircuit, QuantumRegister
from qiskit.circuit.classical import expr
backend.register_conditional_play("x180")
creg = ClassicalRegister(1, "creg")
qreg = QuantumRegister(1, "qreg")
qc = QuantumCircuit(qreg, creg)
condition = expr.equal(creg[0], expr.lift(False))
qc.conditional_play("x180", condition=condition, qubit=qreg[0])
transpiled = transpile(qc, backend, initial_layout=[0])
comp = backend.quantum_circuit_to_qua(transpiled)
The exported OpenQASM wraps the call in its box and addresses the physical qubit directly (creg is a reserved OpenQASM keyword, so the exporter escapes the register name to creg_0):
box {
qm_conditional_play_x180(creg_0[0] == false) $0;
}
qm-qasm receives this as an ordinary provider operation call. Its registered per-qubit macro re-resolves the compile-time pulse and executes qubit.get_pulse("x180").play(condition=qua_condition).
Constraints and errors¶
Only Boolean
expr.Exprconditions are accepted. Use Qiskit’sexprconstructors for comparisons, logical operations, and typed input variables.Run-time selection among pulse names is not supported; register each pulse label separately and choose it while building the circuit.
Inversion and quantum controls are deliberately unsupported. The condition is classical and acts at the QUA pulse-play level.
Registration propagates QuAM errors when the pulse is missing or ambiguous on any active qubit.
backend.quantum_circuit_to_qua(...)rejects an unregistered pulse or a conditional play placed on a physical qubit that has no registered mapping, as part of its general check that every operation is native tobackend.target.QUA conditions the analog pulse only; associated digital markers follow QUA’s normal behavior.
That rejection is
quantum_circuit_to_qua’s responsibility, not the exporter’s:backend.qasm3_exporter(or anyQMOpenQASM3Exporter) has noTargetof its own and does not check registration at all. Calling.dumps(qc)on it directly, instead of going throughquantum_circuit_to_qua, will happily export aConditionalPlaythat was never registered – the resulting OpenQASM 3 simply fails to lower to QUA later.
Pulse support (Qiskit 1.x legacy)¶
When QISKIT_PULSE_AVAILABLE (probed silently at import — Qiskit 2.x does not warn), schedule_to_qua_macro converts gate pulse schedules to QUA. Pulse types are imported only from Pulse-gated APIs; the default circuit-to-QUA path does not load qiskit.pulse.
Supported |
Not supported |
|---|---|
Gate operations as Pulse schedules |
Qiskit Pulse |
QuAM ↔ Pulse channel mapping on |
Kerneled / raw IQ readout (see classified-only note) |
Hybrid readout: circuit-level measure → quantum_circuit_to_qua → comp.outputs (Measurement outputs guide).