Get started with Q-CTRL Performance Management
See the overview and the API reference
IBM Quantum® Functions are a beta feature available only to IBM Quantum Premium Plan, Flex Plan, and On-Prem (through the IBM Quantum Platform API) Plan users. Beta features are subject to change.
The code on this page was developed using the following requirements. We recommend using these versions or newer.
qiskit[all]~=2.3.1 qiskit-ibm-runtime~=0.45.1
Set up and load the function
Fire Opal Performance Management uses Qiskit v2.0.0, which is the recommended version. Supported versions are Qiskit >=v2.0.0.
Authenticate using your IBM Quantum Platform API key, and select the quantum function as follows. (This snippet assumes you've already saved your account to your local environment.)
from qiskit_ibm_catalog import FunctionsCatalog
catalog = FunctionsCatalog(channel="ibm_quantum_platform")# Access function
perf_mgmt = catalog.load("q-ctrl/performance-management")If you want to use a backend that this function does not currently support, reach out to Q-CTRL to add support.
Function sizes
Every job runs at one size: S, M, or L. If the size is too small, the job is rejected. If it is larger than needed, the job runs on a bigger compute profile than the work requires. See the managed workflow documentation for how sizes work in general.
Pass the size to perf_mgmt.run() with the function_size argument. The same sizing rules apply to both Sampler and Estimator.
For Performance Management, the size depends on the number of active physical qubits and the two-qubit gate depth after the circuit is mapped and routed to the selected backend. The sizing calculation uses mapping and routing equivalent to Qiskit's optimization_level=0.
Active qubits are the physical qubits used by circuit operations, excluding barriers. The two-qubit gate depth counts only two-qubit operations, also excluding barriers. Routing can increase both values, so the required size depends on the selected backend as well as the input circuit.
Size | Active qubits | Two-qubit gate depth | Rule |
|---|---|---|---|
S | ≤ 40 | ≤ 40 | Both metrics must satisfy the Small limits. |
M | ≤ 100 | ≤ 100 | At least one metric exceeds its Small limit, but both remain within the Medium limits. |
L | > 100 | > 100 | Either active qubits or two-qubit gate depth exceeds its Medium limit. |
If you submit multiple PUBs, select the largest size required by any circuit in the workload. For example, a mapped circuit with 30 active qubits and a two-qubit gate depth of 60 requires "M".
Calculate the size before submitting
Use the following helper to calculate the size for your PUB tuples. No job is submitted. It maps and routes each circuit to the selected backend with optimization_level=0, then checks the active qubits and two-qubit gate depth, excluding barriers. For multiple PUBs, it returns the largest required size.
# Size calculator for a circuit function.
#
# Input: ``calculate_function_size(circuit, backend, **kwargs)`` -- the circuit and the backend it
# will run on are both required, and the other function inputs arrive as
# ``**kwargs``. The backend is needed because the size depends on its coupling map,
# so pass it by keyword through ``validate_size``:
# ``validate_size("S", circuit, backend=backend)``. A list of PUBs is accepted in
# place of a single circuit, and is sized as the largest of its PUBs.
# Output: ``"S"``, ``"M"`` or ``"L"``, from the number of active qubits and the
# two-qubit-gate depth after mapping the circuit onto ``backend``.
#
# Call ``validate_size`` **once** per job, on everything the job will submit -- the
# whole PUB list, not one PUB at a time. A job runs at a single size, so it has to be sized
# for its heaviest PUB; calling per PUB would also emit one oversize event per PUB.
#
# The mapping is done by ``_pass_manager``, which spells out the passes rather than calling
# ``generate_preset_pass_manager(optimization_level=0)``, so that a future change to the
# preset recipe cannot silently move every vendor's calculates.
#
# Routing is seeded, because routing is stochastic and ``validate_size``
# re-calculates: with an unseeded pass manager the same circuit can be sized differently on
# consecutive calls, so a job could be rejected on a size an identical earlier call accepted.
#
# ``QuantumCircuit.depth(filter_function)`` counts only the instructions for which
# ``filter_function`` returns True, so a two-qubit filter gives the two-qubit-gate depth.
# https://quantum.cloud.ibm.com/docs/api/qiskit/qiskit.circuit.QuantumCircuit#depth
#
# Depends only on Qiskit and ``qiskit-serverless``, so the same file runs in your image and
# in a user's notebook.
from collections.abc import Iterable
from typing import Any, Literal
from qiskit import QuantumCircuit
from qiskit.circuit import Barrier
from qiskit.circuit.equivalence_library import SessionEquivalenceLibrary
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import (
ApplyLayout,
BarrierBeforeFinalMeasurements,
BasisTranslator,
EnlargeWithAncilla,
FilterOpNodes,
FullAncillaAllocation,
HighLevelSynthesis,
SabreSwap,
TrivialLayout,
UnitarySynthesis,
)
from qiskit_serverless import (
ServerlessError,
get_function_size,
get_logger,
send_error,
)
Size = Literal["S", "M", "L"]
_ORDER = {"S": 0, "M": 1, "L": 2}
# Error codes assigned by IBM; see the IBM Quantum error registry.
SIZE_TOO_SMALL_ERROR_CODE = "4600"
SIZE_TOO_LARGE_ERROR_CODE = "4601"
# Limits are provided by IBM
_SMALL_QUBITS, _SMALL_DEPTH_2Q = 40, 40
_MEDIUM_QUBITS, _MEDIUM_DEPTH_2Q = 100, 100
# Any fixed value works; what matters is that it does not change between calls.
_SEED_TRANSPILER = 42
# Added by BarrierBeforeFinalMeasurements so routing cannot move gates past a measurement,
# then removed again once routing is done.
_PROTECTION_BARRIER = "qiskit.transpiler.internal.routing.protection.barrier"
def calculate_function_size(
circuit: QuantumCircuit | Iterable[Any], backend, **kwargs: Any
) -> Size:
"""Return the size ("S", "M" or "L") required to run the function.
``circuit`` is either one ``QuantumCircuit`` or a list of PUBs. For a list, every PUB
circuit is sized on its own and the largest size wins: the job runs on one size, so it
has to be the size the heaviest PUB needs.
"""
circuits = pub_circuits(circuit)
if not circuits:
raise ValueError(
"No circuit to size: pass a QuantumCircuit or a non-empty list of PUBs."
)
return max(
(_calculate_circuit_size(qc, backend, **kwargs) for qc in circuits),
key=_ORDER.__getitem__,
)
def _calculate_circuit_size(
circuit: QuantumCircuit, backend, **kwargs: Any
) -> Size:
"""Return the size required to run a single circuit."""
metrics = _measure(circuit, backend, **kwargs)
if _is_small(metrics):
return "S"
if _is_medium(metrics):
return "M"
return "L"
def pub_circuits(problem: Any) -> list[QuantumCircuit]:
"""Return the circuits in ``problem``: one circuit, or one per PUB in a list of PUBs.
A PUB may be a bare circuit, a tuple/list whose first item is the circuit, or a coerced
``SamplerPub`` / ``EstimatorPub`` (which carries a ``.circuit`` attribute).
"""
if isinstance(problem, QuantumCircuit):
return [problem]
circuits: list[QuantumCircuit] = []
for index, pub in enumerate(problem):
if isinstance(pub, QuantumCircuit):
circuit = pub
elif isinstance(getattr(pub, "circuit", None), QuantumCircuit):
circuit = pub.circuit
elif (
isinstance(pub, (tuple, list))
and pub
and isinstance(pub[0], QuantumCircuit)
):
circuit = pub[0]
else:
raise ValueError(f"PUB #{index} has no QuantumCircuit to size.")
circuits.append(circuit)
return circuits
def _pass_manager(target) -> PassManager:
"""Return the pass manager used to map a circuit onto ``target``.
This spells out the passes that ``generate_preset_pass_manager(optimization_level=0)``
assembles today, so that a future change to the level-0 recipe cannot silently move
every vendor's size calculates. It is the pass list that is pinned, not the passes: a
new Qiskit release can still change what ``SabreSwap`` or ``BasisTranslator`` does.
Stages, mirroring the preset: unroll anything wider than two qubits, lay the circuit
out trivially and pad it to the backend width, route it, then translate to the
backend basis. Level 0 runs no optimization stage.
"""
basis = list(target.operation_names)
library = SessionEquivalenceLibrary
return PassManager(
[
UnitarySynthesis(
basis, approximation_degree=1.0, min_qubits=3, target=target
),
HighLevelSynthesis(
target=target,
equivalence_library=library,
basis_gates=basis,
min_qubits=3,
),
BasisTranslator(library, basis, target=target, min_qubits=3),
TrivialLayout(target),
FullAncillaAllocation(target),
EnlargeWithAncilla(),
ApplyLayout(),
BarrierBeforeFinalMeasurements(label=_PROTECTION_BARRIER),
SabreSwap(
target, heuristic="basic", seed=_SEED_TRANSPILER, trials=5
),
FilterOpNodes(lambda node: node.label != _PROTECTION_BARRIER),
UnitarySynthesis(basis, approximation_degree=1.0, target=target),
HighLevelSynthesis(
target=target,
equivalence_library=library,
basis_gates=basis,
use_qubit_indices=True,
),
BasisTranslator(library, basis, target=target),
]
)
def _count(isa: QuantumCircuit) -> dict:
"""Return the number of active qubits and the two-qubit-gate depth of a mapped circuit.
``isa.num_qubits`` would be the width of the whole backend, so only the qubits that
carry an operation are counted.
"""
active = {
q
for instr in isa.data
if not isinstance(instr.operation, Barrier)
for q in instr.qubits
}
return {
"num_qubits": len(active),
"depth_2q": isa.depth(
filter_function=lambda instr: len(instr.qubits) == 2
and not isinstance(instr.operation, Barrier)
),
}
def _measure(circuit: QuantumCircuit, backend, **kwargs: Any) -> dict: # pylint: disable=unused-argument
"""Map ``circuit`` onto ``backend`` and return its metrics."""
return _count(_pass_manager(backend.target).run(circuit))
def _is_small(metrics: dict) -> bool:
"""Determine if the metrics fit T-size 'S'."""
return (
metrics["num_qubits"] <= _SMALL_QUBITS
and metrics["depth_2q"] <= _SMALL_DEPTH_2Q
)
def _is_medium(metrics: dict) -> bool:
"""Determine if the metrics fit T-size 'M'."""
return (
metrics["num_qubits"] <= _MEDIUM_QUBITS
and metrics["depth_2q"] <= _MEDIUM_DEPTH_2Q
)
def validate_size(
circuit: QuantumCircuit | Iterable[Any], backend, **kwargs: Any
) -> None:
"""Call once at the start of your function, on everything the job will submit.
Compare the size the job was given with the calculated size and log both. Raise if
the given size is smaller than the calculation; report a non-fatal event and continue
if it is larger. Pass the whole PUB list rather than calling this per PUB: the job
runs at one size, and a per-PUB call would emit one oversize event per PUB."""
logger = get_logger()
provided = get_function_size()
if not provided:
# Empty on non-Fleets (Ray) jobs, where sizes do not apply.
logger.warning(
"No function size was given to this job; skipping the size check."
)
return
provided = provided.upper()
expected = calculate_function_size(circuit, backend, **kwargs)
logger.info(
"Function size given: '%s'; calculated size: '%s'.",
provided,
expected,
)
if _ORDER[provided] < _ORDER[expected]:
logger.error(
"Size '%s' is too small; the calculated size is '%s'.",
provided,
expected,
)
raise ServerlessError(
code=SIZE_TOO_SMALL_ERROR_CODE,
message=f"Size '{provided}' is too small for this problem; expected '{expected}' or larger.",
)
if _ORDER[provided] > _ORDER[expected]:
logger.warning(
"Size '%s' is larger than this problem needs; the calculated size is '%s'.",
provided,
expected,
)
send_error(
code=SIZE_TOO_LARGE_ERROR_CODE,
message="The specified function size is larger than this job requires.",
exception="FunctionSizeTooLarge",
args={
"provided_size": provided,
"calculated_size": expected,
"solution": (
"No action is required and the job completed normally. To reduce "
"cost, use a smaller function size for jobs of this kind."
),
},
)If the size is too small, the job fails with error 4600, and the message names the size to use instead. If it is larger than needed, the job runs normally and records a 4601 advisory event. See the managed workflow documentation to learn more.
Estimator primitive
Estimator example
Use Fire Opal Performance Management's Estimator primitive to determine the expectation value of a single circuit-observable pair.
In addition to the qiskit-ibm-catalog and qiskit packages, you will also use the numpy package to run this example. You can install this package by uncommenting the following cell if you are running this example in a notebook using the IPython kernel.
# %pip install numpy1. Create the circuit
As an example, generate a random Hermitian operator and an observable to input to the Performance Management function.
import numpy as np
from qiskit.circuit.library import iqp
from qiskit.quantum_info import random_hermitian, SparsePauliOp
n_qubits = 37
# Generate a random circuit
mat = np.real(random_hermitian(n_qubits, seed=1234))
circuit = iqp(mat)
circuit.measure_all()
# Define observables as a string
observable = SparsePauliOp("Z" * n_qubits)# Create PUB tuple
estimator_pubs = [(circuit, observable)]2. Run the circuit
Calculate the function size for estimator_pubs on the selected backend, then pass the returned value to perf_mgmt.run through function_size. For the sizing rules, see Function sizes. You can also specify the number of shots.
backend = catalog.least_busy()
estimator_size = calculate_function_size(estimator_pubs, backend)
print(f"Workload size: {estimator_size}")Output:
Workload size: M
# Run the circuit using Estimator
qctrl_estimator_job = perf_mgmt.run(
primitive="estimator",
pubs=estimator_pubs,
backend_name=backend.name,
function_size=estimator_size,
)Check your quantum function workload's status:
qctrl_estimator_job.status()Output:
'DONE'
3. Retrieve the result
# Retrieve the counts from the result list
result = qctrl_estimator_job.result()The results have the same format as an Estimator result:
import numpy
result_str = str(result)
with numpy.printoptions(threshold=200):
print(
f"The result of the submitted job had {len(result)} PUB "
f"and has a value:\n {result[0]}\n"
)
print("The associated PubResult of this job has the following DataBins:")
print(f"{result[0].data}\n")
print(f"And this DataBin has attributes: {result[0].data.keys()}")
print("The expectation values measured from this PUB are:")
print(f"{result[0].data.evs}")Output:
The result of the submitted job had 1 PUB and has a value:
PubResult(data=DataBin(evs=np.ndarray(<shape=(1,), dtype=float64>), stds=np.ndarray(<shape=(1,), dtype=float64>)), metadata={'precision': None})
The associated PubResult of this job has the following DataBins:
DataBin(evs=np.ndarray(<shape=(1,), dtype=float64>), stds=np.ndarray(<shape=(1,), dtype=float64>))
And this DataBin has attributes: dict_keys(['evs', 'stds'])
The expectation values measured from this PUB are:
[0.00252317]
Sampler primitive
Sampler example
Use Fire Opal Performance Management's Sampler primitive to run a Bernstein–Vazirani circuit. This algorithm, used to find a hidden string from the outputs of a black box function, is a common benchmarking algorithm because there is a single correct answer.
1. Create the circuit
Define the correct answer to the algorithm, the hidden bitstring, and the Bernstein–Vazirani circuit. You can adjust the width of the circuit by simply changing the circuit_width.
import qiskit
circuit_width = 14
hidden_bitstring = "1" * circuit_width
# Create circuit, reserving one qubit for BV oracle
bv_circuit = qiskit.QuantumCircuit(circuit_width + 1, circuit_width)
bv_circuit.x(circuit_width)
bv_circuit.h(range(circuit_width + 1))
for input_qubit, bit in enumerate(reversed(hidden_bitstring)):
if bit == "1":
bv_circuit.cx(input_qubit, circuit_width)
bv_circuit.barrier()
bv_circuit.h(range(circuit_width + 1))
bv_circuit.barrier()
for input_qubit in range(circuit_width):
bv_circuit.measure(input_qubit, input_qubit)
# Create PUB tuple
sampler_pubs = [(bv_circuit,)]2. Run the circuit
Calculate the function size for sampler_pubs on the selected backend, then pass the returned value to perf_mgmt.run through function_size. You can also specify the number of shots.
# Calculate the workload size for the selected backend
sampler_size = calculate_function_size(sampler_pubs, backend)
print(f"Workload size: {sampler_size}")Output:
Workload size: M
# Run the circuit using Sampler
qctrl_sampler_job = perf_mgmt.run(
primitive="sampler",
pubs=sampler_pubs,
backend_name=backend.name,
function_size=sampler_size,
)Check your quantum function workload's status or return results as follows:
# Print the ID so you can use it later, if necessary
print(qctrl_sampler_job.job_id)
qctrl_sampler_job.status()Output:
d35c9efc-1542-461d-ae19-5485cab3fd80
'DONE'
3. Retrieve the result
# Retrieve the job results
sampler_result = qctrl_sampler_job.result()# Get results for the first (and only) PUB
pub_result = sampler_result[0]
counts = pub_result.data.c.get_counts()
print("Counts for the meas output register (limited to 30 results):")
for i, (bitstring, count) in enumerate(counts.items()):
if i >= 50:
print(f" ... ({len(counts) - 30} more items)")
break
print(f" {bitstring}: {count}")Output:
Counts for the meas output register (limited to 30 results):
11111111111111: 2715
11111101111111: 134
11111111110111: 102
11111011111111: 73
11111111111110: 66
00000000000111: 60
11111111111101: 59
11111110111111: 50
11110111111111: 48
11111111101111: 47
11111111011111: 34
11011111111111: 30
10111111111111: 27
00111111111111: 24
00011111111111: 23
01111111111111: 22
00000000010111: 20
00000001110111: 19
00000000000001: 18
11111110011111: 18
00000011111111: 16
11101111111111: 15
00000001111111: 14
00001011111111: 11
00000000111111: 11
00001111111111: 10
00000000000010: 9
00000000001111: 9
00000000000011: 8
01011111111111: 8
00000011110111: 8
10011111111111: 7
00000000011111: 7
00000000000000: 7
11111110000111: 6
11111011110111: 5
11111001111111: 5
01111011111111: 5
00000010000111: 5
11111111010111: 4
00000111111111: 4
00111101111111: 4
11111110010111: 4
11010111111111: 4
11111110110111: 4
01111111111101: 3
11110011111111: 3
11111110101111: 3
00000000000101: 3
11111101110111: 3
... (195 more items)
3. Plot the top bitstrings
Plot the bitstring with the highest counts to see if the hidden bitstring was the mode.
import matplotlib.pyplot as plt
def plot_top_bitstrings(counts_dict, hidden_bitstring=None):
# Sort and take the top 100 bitstrings
top_100 = sorted(counts_dict.items(), key=lambda x: x[1], reverse=True)[
:100
]
if not top_100:
print("No bitstrings found in the input dictionary.")
return
# Unzip the bitstrings and their counts
bitstrings, counts = zip(*top_100)
# Assign colors: purple if the bitstring matches hidden_bitstring,
# otherwise gray
colors = [
"#680CE9" if bit == hidden_bitstring else "gray" for bit in bitstrings
]
# Create the bar plot
plt.figure(figsize=(15, 8))
plt.bar(
range(len(bitstrings)), counts, tick_label=bitstrings, color=colors
)
# Rotate the bitstrings for better readability
plt.xticks(rotation=90, fontsize=8)
plt.xlabel("Bitstrings")
plt.ylabel("Counts")
plt.title("Top 100 Bitstrings by Counts")
# Show the plot
plt.tight_layout()
plt.show()The hidden bitstring is highlighted in purple, and it should be the bitstring with the highest number of counts.
plot_top_bitstrings(counts, hidden_bitstring)Output:
Next steps
- Tune your workloads with advanced techniques for Q-CTRL Performance Management.
- Visit the API reference for this quantum function.
- Try the Transverse-Field Ising Model with Q-CTRL's Performance Management tutorial.
- Try the Quantum Phase Estimation with Q-CTRL's quantum functions tutorial.
- Learn how to choose a problem size.
- Review Mundada P. S., et al. (2023). Experimental Benchmarking of an Automated Deterministic Error-Suppression Workflow for Quantum Algorithms. Physical Review Applied, 20, 2.
- Review Kanno, S., et al. (2025). Tensor-based quantum phase difference estimation for large-scale demonstration. arXiv preprint arXiv:2408.04946.
- Review SoftBank Corp, Demonstration Experiment of a Communication Service Fault Diagnosis System Using Quantum Machine Learning (blog), 30 August, 2024.
- Review Yamauchi, H., et al. (2024). Parametrized Energy-Efficient Quantum Kernels for Network Service Fault Diagnosis. arXiv preprint arXiv:2405.09724v1.
- Review Yamauchi, H., et al. (2025). Quantum spectroscopy of topological dynamics via a supersymmetric Hamiltonian. arXiv preprint arXiv:2511.23169v1.
- Review Wang, Y., et al. (2025). Δ-Motif: Subgraph Isomorphism at Scale via Data-Centric Parallelism. arXiv preprint arXiv:2508.21287.
- Review Paterakis, N. G., et al. (2025). Quantum Computing in the Computational Landscape of Power Electronics: Vision and Reality. arXiv preprint arXiv:2507.02577.
- Review Gharibyan, H., et al. (2023). Hierarchical Learning for Quantum ML: Novel Training Technique for Large-Scale Variational Quantum Circuits. arXiv preprint arXiv:2311.12929.
- Review the Mitsubishi Chemical Corp case study.
- Review the Redacted bank case study.
- Review the BlueQubit case study.