Usage guide

Native interface

The library implements the IBM-prefixed QDMI 1.4.0 device interface: device lifecycle, sessions, metadata queries, and jobs. Supported program formats are OpenQASM 3, QPY, and the Executor extension. Child-device enumeration is unsupported.

The generated QDMI declaration reference describes the implemented device functions, types, and IBM-specific constants.

Session configuration

The repository’s .env.example lists connection variables and optional client settings. The device reads process environment values; it does not load .env files.

Include ibm_qdmi/device.h and ibm-qdmi-device/constants.h. Set parameters before initializing a session. Strings include the terminating null byte in size; embedded null bytes are rejected. A null value checks support without changing a parameter. Successful initialization freezes configuration. Failed initialization leaves the session configurable and safe to free.

Parameter

Value

QDMI_DEVICE_SESSION_PARAMETER_TOKEN

IBM Cloud API key, not an IAM bearer token; otherwise use an explicit key file, then IBM_QUANTUM_API_KEY.

QDMI_DEVICE_SESSION_PARAMETER_AUTHFILE

Optional UTF-8 path to a file containing only the API key.

IBM_QDMI_DEVICE_SESSION_PARAMETER_BACKEND

Backend name; defaults to IBM_QUANTUM_BACKEND; aliases session CUSTOM1.

IBM_QDMI_DEVICE_SESSION_PARAMETER_INSTANCE_CRN

Instance CRN; defaults to IBM_QUANTUM_INSTANCE_CRN; aliases session CUSTOM2.

IBM_QDMI_DEVICE_SESSION_PARAMETER_REQUEST_TIMEOUT

Positive decimal string of milliseconds from 1 through 2,147,483,647; default 30000; aliases session CUSTOM3.

QDMI_DEVICE_SESSION_PARAMETER_BASEURL

Optional API root ending in /api, without /v1. Defaults from the CRN region.

QDMI_DEVICE_SESSION_PARAMETER_AUTHURL

Optional full IAM token endpoint; defaults to https://iam.cloud.ibm.com/identity/token.

Default API roots are https://quantum.cloud.ibm.com/api for us-east and https://eu-de.quantum.cloud.ibm.com/api for eu-de. Other regions require an explicit root. Custom endpoints must use HTTPS; HTTP is accepted only for localhost, 127.0.0.1, and [::1] loopback tests. Certificate verification stays enabled, and redirects are not followed. Configure only trusted endpoints. The API key, backend name, and instance CRN must resolve to nonempty values. Explicit parameters take precedence over environment values, including an explicit empty value, which fails validation. Defaults are read during session initialization. A failed attempt does not freeze them; an initialized session retains its configuration when the environment changes.

Credential precedence is explicit token, explicit key file, then IBM_QUANTUM_API_KEY. A selected invalid or unreadable file never falls back to environment credentials. Files contain one raw UTF-8 key, optionally followed by LF or CRLF. Empty content, embedded newlines, and null bytes are rejected; other whitespace is preserved. Files are read during initialization. Unreadable files return QDMI_ERROR_PERMISSIONDENIED; malformed content or an empty path returns QDMI_ERROR_INVALIDARGUMENT. Saved Qiskit accounts are not read.

The API key is exchanged at IAM. Backend requests use the resulting bearer token, Service-CRN, and IBM-API-Version: 2026-04-15. Tokens and their expiry belong to individual sessions. Refresh occurs before expiry and once after an HTTP 401; the authenticated GET is retried once. GET requests retry temporary connection failures and HTTP 429, 500, 502, 503, and 504 responses at most twice. Retries wait 100 then 200 milliseconds, or longer when Retry-After requires it. Authentication, requests, and backoff share the configured timeout, which defaults to 30 seconds. A shorter job-wait deadline takes precedence. Retries stop when the next delay cannot fit within that budget. POST requests, including IAM exchanges, job submission, and cancellation, are never retried. See IBM authentication.

Requests on different jobs and independent queries can run concurrently. Operations on one job and IAM refresh within a session are serialized. Job-wait deadlines include lock and authentication waits.

Query behavior

Initialization reads backend configuration and calibration properties into a session snapshot. Site and operation handles remain stable until that session is freed and cannot be used with another session. Create a new session for a fresh calibration snapshot. Status and queue queries fetch current backend status.

Queries

Behavior

Device name/version

IBM backend name/version.

Library version

Version of the QDMI library used to build the device.

Qubit count, sites, coupling

Physical indices and directed pairs from backend configuration.

Operations

Basis gates and advertised measure, reset, and delay. Configuration and calibration provide signatures and physical site tuples.

T1, T2, gate duration

Rounded to the nearest femtosecond. Duration unit fs, scale factor 1.

Gate fidelity

1 - gate_error, where IBM reports a finite error in [0, 1].

Device status

OFFLINE when unavailable; otherwise BUSY for a nonempty queue and IDLE for an empty queue. Missing availability is unsupported.

Queue length

Nonnegative number of queued jobs.

Measurement calibration uses readout_length and 1 - readout_error from qubit properties. Site-dependent duration and fidelity require a supported ordered site tuple. Configuration tuples take precedence over calibration tuples; contradictions fail initialization. No connectivity is inferred from gate names. Calibration flags that mark a qubit or gate as non-operational exclude its operation tuples and calibrations. Physical site indices, the qubit count, and the configuration coupling map remain available. Absent operational flags do not exclude tuples. Calibration values describe the reported gate calibration, not a parameter-dependent model. Missing optional values, unknown units, negative durations, overflow, and invalid fidelities return QDMI_ERROR_NOTSUPPORTED, never fabricated zero values. A missing calibration endpoint (HTTP 404) permits initialization without those optional values. Malformed structural metadata fails initialization.

IBM_QDMI_DEVICE_PROPERTY_TIMING (QDMI_DEVICE_PROPERTY_CUSTOM4) returns a null-terminated JSON object with schema ibm.timing.v1 and the sampling interval dt in seconds. When IBM reports them, granularity, min_length, pulse_alignment, and acquire_alignment are positive integers in samples. The query returns QDMI_ERROR_NOTSUPPORTED if the sampling interval is missing or any reported timing value is invalid.

Advertised rzz operations expose their inclusive angle interval [0, pi/2] in radians through IBM_QDMI_OPERATION_PROPERTY_MQT_PARAMETERS (QDMI_OPERATION_PROPERTY_CUSTOM2). The null-terminated UTF-8 JSON is:

{
  "schema": "mqt.operation-parameters.v1",
  "alternatives": [{"bounds": [[0, 1.5707963267948966]]}]
}

This experimental contract is shared with MQT Core and is not a standard QDMI property. Other operations, including unrestricted rx, return QDMI_ERROR_NOTSUPPORTED. The inclusive interval follows the IBM Runtime SDK’s angle bounds.

Queries honor the QDMI size-query contract. Insufficient output buffers and invalid arguments return QDMI_ERROR_INVALIDARGUMENT. Uninitialized-session queries return QDMI_ERROR_BADSTATE. HTTP authentication failures map to QDMI_ERROR_PERMISSIONDENIED, a missing backend to QDMI_ERROR_NOTFOUND, request deadlines to QDMI_ERROR_TIMEOUT, allocation failures to QDMI_ERROR_OUTOFMEM, and other transport/server/parsing failures to QDMI_ERROR_FATAL. Errors never include raw server responses or credentials.

Include ibm-qdmi-device/diagnostics.h and call IBM_QDMI_device_last_diagnostic() immediately after a failed call for its fixed diagnostic category. It describes the last QDMI call on the current thread; successful calls reset it to NONE. Categories distinguish transport, rate limits, service errors, failed jobs, and internal errors without exposing server text or credentials. The diagnostic query sends no request.

The supported backend response shapes follow the IBM backend API. Other QDMI properties return QDMI_ERROR_NOTSUPPORTED.

Query example

This C++ function accepts configuration supplied by its caller. Calling it contacts IBM and requires authorization. Keep credentials out of source files. The function owns the device lifecycle; free every session before finalization.

#include <ibm-qdmi-device/constants.h>
#include <ibm_qdmi/device.h>

#include <cstring>

int queryQubitCount(const char *apiKey, const char *crn, const char *backend,
                    size_t *qubits) {
  if (!apiKey || !crn || !backend || !qubits) {
    return QDMI_ERROR_INVALIDARGUMENT;
  }
  int result = IBM_QDMI_device_initialize();
  if (result != QDMI_SUCCESS) {
    return result;
  }
  IBM_QDMI_Device_Session session = nullptr;
  result = IBM_QDMI_device_session_alloc(&session);
  const auto set = [&](QDMI_Device_Session_Parameter parameter,
                       const char *text) {
    if (result == QDMI_SUCCESS) {
      result = IBM_QDMI_device_session_set_parameter(
          session, parameter, std::strlen(text) + 1, text);
    }
  };
  set(QDMI_DEVICE_SESSION_PARAMETER_TOKEN, apiKey);
  set(IBM_QDMI_DEVICE_SESSION_PARAMETER_INSTANCE_CRN, crn);
  set(IBM_QDMI_DEVICE_SESSION_PARAMETER_BACKEND, backend);
  if (result == QDMI_SUCCESS) {
    result = IBM_QDMI_device_session_init(session);
  }
  if (result == QDMI_SUCCESS) {
    result = IBM_QDMI_device_session_query_device_property(
        session, QDMI_DEVICE_PROPERTY_QUBITSNUM, sizeof(*qubits), qubits, nullptr);
  }
  IBM_QDMI_device_session_free(session);
  const int finalized = IBM_QDMI_device_finalize();
  return result == QDMI_SUCCESS ? finalized : result;
}

Jobs and results

IBM_QDMI_device_job_set_programs accepts an ordered list of programs with a common format and shot count. Each text size includes exactly one final null byte. The setter validates and copies the complete list atomically; rejection preserves the previous programs and format. Pass a nonzero count and a null program pointer to probe support with the current job parameters.

OpenQASM and QPY shots default to 1,024 and must be positive. The number of programs times the shot count must not exceed IBM’s 10-million-execution limit. Setting programs or changing shots beyond this limit returns QDMI_ERROR_NOTSUPPORTED without changing the configuration.

The custom IBM_QDMI_DEVICE_JOB_PARAMETER_MAX_EXECUTION_TIME parameter takes a uint64_t number of seconds from 1 through 10,800, defaulting to 60. This bounds QPU execution time, not queue or wall-clock time. A null parameter value probes support without changing configuration.

Submit valid, bound OpenQASM 3 compiled for the backend’s native operations and physical qubit indices. MQT Core’s compiler and Qiskit adapter prepare programs. The device supplies missing ECR/RZZ definitions for OpenQASM import. These definitions use built-in gates and need no include file. Authored gate definitions and includes remain unchanged. IBM validates instructions; the device reads classical declarations to reconstruct results in declaration order.

Declare all classical output bits at the top level with fixed, positive sizes: bit[n] name;, bit name;, or creg name[n];. Register names must be distinct. Every declared classical register contributes to the result. Explicit output qualifiers are unsupported, as in Qiskit’s OpenQASM importer. Scoped classical declarations, parameter inputs, annotations, pragmas, and includes other than stdgates.inc are unsupported because they can hide or change the output layout.

For QDMI_PROGRAM_FORMAT_QPY, pass raw QPY 17 bytes with exact sizes and no null terminator. Each program contains one bound circuit compiled for the backend’s physical qubits. Classical registers must partition its bits in declaration order; loose bits, overlapping registers, and standalone classical variables are unsupported. IBM returns samples by register name, so the device reads their order and widths to assemble QDMI bitstrings. Qiskit and IBM validate instructions and the remaining file contents.

The device handles compression and base64 encoding. Retrieval restores the raw QPY bytes; job_get_program reports their exact size. For an open device:

from pathlib import Path
from mqt.core.qdmi import ProgramFormat

program = Path("compiled.qpy").read_bytes()
job = device.submit_job(program, ProgramFormat.QPY, num_shots=128)
job.wait(60)
counts = job.get_counts()
original = job.get_program(bytes)

See Qiskit execution for conditional circuits.

Each OpenQASM or QPY submission creates one Sampler V2 job with an ordered circuit list and classified measurements. Twirling is disabled; dynamical decoupling is disabled by default and can be configured per job. Submission is never automatically retried, including after an authentication failure or a lost response. A failed submission freezes that handle. An ambiguous response may mean IBM accepted the job; inspect the platform before creating a replacement.

Job ID, format, shots, and program count (QDMI_DEVICE_JOB_PROPERTY_PROGRAMSNUM) are queryable. IBM_QDMI_device_job_get_program retrieves the original bytes at a zero-based program index. For a retrieved remote job, OpenQASM includes any declarations added for transport. Size queries use a null output buffer. An unset supported property returns QDMI_ERROR_BADSTATE; queue position returns QDMI_ERROR_NOTSUPPORTED. A job retains its session resources; freeing a session or job handle does not cancel a remote job. Free every job and session before device finalization.

job_check polls once. job_wait accepts a timeout in seconds, with zero meaning no overall deadline. The deadline includes authentication and HTTP requests. Timeout leaves the remote job active; cancellation is a separate request. Waiting succeeds when a job finishes, is canceled, or fails. Call job_check after waiting to distinguish these states. Cancellation racing with completion returns QDMI_ERROR_INVALIDARGUMENT and preserves the completed state.

IBM_QDMI_device_job_get_results selects a program by its zero-based input index. Sampler results contain comma-separated binary shots, comma-separated histogram keys, and a matching size_t count array. Strings include their terminating null byte. Bits follow classical declaration order, with the highest bit index on the left. Leading zeros and shot order are preserved. Results of unfinished, canceled, or failed jobs return QDMI_ERROR_BADSTATE. Results not yet available after completion return QDMI_ERROR_BADSTATE; malformed results fail rather than fabricating counts. Completed results are cached. Statevectors and probabilities are unsupported. IBM reports aggregate outcomes; indexed program status returns QDMI_ERROR_NOTSUPPORTED.

Retrieval by job ID creates a read-only local handle without resubmitting. It requires the same backend and retained input parameters. Sampler retrieval restores ordered plain-JSON circuit lists with a common shot count and each program’s classical register layout. Executor retrieval supports the v2.0 extension described below. Private jobs are unsupported. See the IBM jobs API.

Dynamical decoupling

Set IBM_QDMI_DEVICE_JOB_PARAMETER_DYNAMICAL_DECOUPLING (job CUSTOM2) before submission to configure IBM Runtime’s dynamical decoupling. Its value is a null-terminated JSON object; include the terminator in size.

Field

Accepted values

Default

enable

JSON boolean

false

sequence_type

"XX", "XpXm", "XY4"

"XX"

extra_slack_distribution

"middle", "edges"

"middle"

scheduling_method

"alap", "asap"

"alap"

skip_reset_qubits

JSON boolean

false

These defaults follow IBM’s dynamical-decoupling options. Each assignment replaces the previous object and fills omitted fields with these defaults. An empty object resets all options. A null pointer probes support. Invalid options return QDMI_ERROR_INVALIDARGUMENT without changing configuration. Options are frozen after submission starts and on retrieved jobs.

For a configurable native job:

const char options[] = R"({"enable":true,"sequence_type":"XpXm"})";
const int status = IBM_QDMI_device_job_set_parameter(
    job, IBM_QDMI_DEVICE_JOB_PARAMETER_DYNAMICAL_DECOUPLING,
    sizeof(options), options);

With MQT Core, pass the JSON string directly to the QDMI device’s submission method. This example assumes an authenticated IBM device and a native, bound OpenQASM 3 program. Submission creates a paid job and requires an authorized backend and budget:

import json

from mqt.core.qdmi import ProgramFormat

job = device.submit_job(
    program,
    ProgramFormat.QASM3,
    num_shots=128,
    custom2=json.dumps({"enable": True, "sequence_type": "XpXm"}),
)
job.wait(900)
shots = job.get_shots()

The shared Qiskit backend.run() interface does not expose this custom option. IBM validates compatibility with the selected backend and circuit. Service rejection follows the normal submission error contract and is never retried.

Python package

See the Python package guide for installed paths, package metadata, and the information CLI. The optional Qiskit integration exposes ibm.qdmi.qiskit.IBMBackend through MQT Core’s shared adapter.

Executor extension

IBM_QDMI_PROGRAM_FORMAT_EXECUTOR aliases QDMI_PROGRAM_FORMAT_CUSTOM1. Pass it to IBM_QDMI_device_job_set_programs with exactly one null-terminated Executor v2.0 params object, rather than a complete REST job request. It contains schema_version, quantum_program, and optional options. The native device validates the envelope, positive shot count, and nonempty item list; IBM’s encoder and service validate circuit and samplex contents.

quantum_program.shots supplies SHOTSNUM. Setting the separate SHOTSNUM parameter or the Sampler dynamical-decoupling parameter is unsupported for this format. Selecting Executor after setting those parameters is also unsupported. The maximum-execution-time parameter applies to both formats.

Read IBM_QDMI_JOB_RESULT_EXECUTOR (QDMI_JOB_RESULT_CUSTOM1) to obtain the null-terminated result JSON. Size queries include the terminating null byte. The device caches the complete result, including tensor encodings and metadata. Standard shots and histogram result queries return QDMI_ERROR_NOTSUPPORTED for Executor jobs. The custom result is unsupported for Sampler jobs. Job status, waiting, cancellation, and retrieval by ID use the standard QDMI API.

Compiler payload capabilities

On backends advertising if_else, device property CUSTOM3 returns versioned mqt.payload-capabilities.v1 JSON. Other backends return NOTSUPPORTED. The property advertises forward branching with one nesting level, register-equality conditions of at most 32 bits, and unitary branch bodies. MQT Core applies these limits during compilation and native serialization, including QPY submission.