Primitive inputs and outputs
Package versions
The code on this page was developed using the following requirements. We recommend using these versions or newer.
qiskit[all]~=1.3.1
qiskit-ibm-runtime~=0.34.0
qiskit-aer~=0.15.1
qiskit-serverless~=0.18.0
qiskit-ibm-catalog~=0.2
qiskit-addon-sqd~=0.8.1
qiskit-addon-utils~=0.1.0
qiskit-addon-mpf~=0.2.0
scipy~=1.14.1
qiskit-addon-aqc-tensor~=0.1.2
qiskit-addon-obp~=0.1.0
scipy~=1.14.1
pyscf~=2.7.0
This page gives an overview of the inputs and outputs of the Qiskit Runtime primitives that execute workloads on IBM Quantum™ compute resources. These primitives provide you with the ability to efficiently define vectorized workloads by using a data structure known as a Primitive Unified Bloc (PUB). These PUBs are the fundamental unit of work a QPU needs to execute these workloads. They are used as inputs to the run()
method for the Sampler and Estimator primitives, which execute the defined workload as a job. Then, after the job has completed, the results are returned in a format that is dependent on both the PUBs used as well as the runtime options specified from the Sampler or Estimator primitives.
Overview of PUBs
When invoking a primitive's run()
method, the main argument that is required is a list
of one or more tuples -- one for each circuit being executed by the primitive. Each of these tuples is considered a PUB, and the required elements of each tuple in the list depends on the the primitive used. The data provided to these tuples can also be arranged in a variety of shapes to provide flexibility in a workload through broadcasting -- the rules of which are described in a following section.
Estimator PUB
For the Estimator primitive, the format of the PUB should contain at most four values:
- A single
QuantumCircuit
, which may contain one or moreParameter
objects - A list of one or more observables, which specify the expectation values to estimate, arranged into an array (for example, a single observable represented as a 0-d array, a list of observables as a 1-d array, and so on). The data can be in any one of the
ObservablesArrayLike
format such asPauli
,SparsePauliOp
,PauliList
, orstr
. - A collection of parameter values to bind the circuit against. This can be specified as a single array-like object where the last index is over circuit
Parameter
objects, or omitted (or equivalently, set toNone
) if the circuit has noParameter
objects. - (Optionally) a target precision for expectation values to estimate
Sampler PUB
For the Sampler primitive, the format of the PUB tuple contains at most three values:
- A single
QuantumCircuit
, which may contain one or moreParameter
objects Note: These circuits should also include measurement instructions for each of the qubits to be sampled. - A collection of parameter values to bind the circuit against (only needed if any
Parameter
objects are used that must be bound at runtime) - (Optionally) a number of shots to measure the circuit with
The following code demonstrates an example set of vectorized inputs to the Estimator
primitive and executes them on an IBM® backend as a single RuntimeJobV2
object.
from qiskit_ibm_runtime import QiskitRuntimeService
from qiskit.circuit import Parameter, QuantumCircuit
from qiskit_ibm_runtime import (
EstimatorV2 as Estimator,
SamplerV2 as Sampler,
)
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit.quantum_info import SparsePauliOp
import numpy as np
# Instantiate runtime service and get
# the least busy backend
service = QiskitRuntimeService()
backend = service.least_busy(operational=True, simulator=False)
# Define a circuit with two parameters.
circuit = QuantumCircuit(2)
circuit.h(0)
circuit.cx(0, 1)
circuit.ry(Parameter("a"), 0)
circuit.rz(Parameter("b"), 0)
circuit.cx(0, 1)
circuit.h(0)
# Transpile the circuit
pm = generate_preset_pass_manager(optimization_level=1, backend=backend)
transpiled_circuit = pm.run(circuit)
layout = transpiled_circuit.layout
# Now define a sweep over parameter values, the last axis of dimension 2 is
# for the two parameters "a" and "b"
params = np.vstack(
[
np.linspace(-np.pi, np.pi, 100),
np.linspace(-4 * np.pi, 4 * np.pi, 100),
]
).T
# Define three observables. The inner length-1 lists cause this array of
# observables to have shape (3, 1), rather than shape (3,) if they were
# omitted.
observables = [
[SparsePauliOp(["XX", "IY"], [0.5, 0.5])],
[SparsePauliOp("XX")],
[SparsePauliOp("IY")],
]
# Apply the same layout as the transpiled circuit.
observables = [
[observable.apply_layout(layout) for observable in observable_set]
for observable_set in observables
]
# Estimate the expectation value for all 300 combinations of observables
# and parameter values, where the pub result will have shape (3, 100).
#
# This shape is due to our array of parameter bindings having shape
# (100, 2), combined with our array of observables having shape (3, 1).
estimator_pub = (transpiled_circuit, observables, params)
# Instantiate the new estimator object, then run the transpiled circuit
# using the set of parameters and observables.
estimator = Estimator(mode=backend)
job = estimator.run([estimator_pub])
result = job.result()
Broadcasting rules
The PUBs aggregate elements from multiple arrays (observables and parameter values) by following the same broadcasting rules as NumPy. This section briefly summarizes those rules. For a detailed explanation, see the NumPy broadcasting rules documentation.
Rules:
- Input arrays do not need to have the same number of dimensions.
- The resulting array will have the same number of dimensions as the input array with the largest dimension.
- The size of each dimension is the largest size of the corresponding dimension.
- Missing dimensions are assumed to have size one.
- Shape comparisons start with the rightmost dimension and continue to the left.
- Two dimensions are compatible if their sizes are equal or if one of them is 1.
Examples of array pairs that broadcast:
A1 (1d array): 1
A2 (2d array): 3 x 5
Result (2d array): 3 x 5
A1 (3d array): 11 x 2 x 7
A2 (3d array): 11 x 1 x 7
Result (3d array): 11 x 2 x 7
Examples of array pairs that do not broadcast:
A1 (1d array): 5
A2 (1d array): 3
A1 (2d array): 2 x 1
A2 (3d array): 6 x 5 x 4 # This would work if the middle dimension were 2, but it is 5.
EstimatorV2
returns one expectation value estimate for each element of the broadcasted shape.
Here are some examples of common patterns expressed in terms of array broadcasting. Their accompanying visual representation is shown in the figure that follows:
Parameter value sets are represented by n x m arrays, and observable arrays are represented by one or more single-column arrays. For each example in the previous code, the parameter value sets are combined with their observable array to create the resulting expectation value estimates. Example 1 (broadcast single observable) has a parameter value set that is a 5x1 array and a 1x1 observables array. The one item in the observables array is combined with each item in the parameter value set to create a single 5x1 array where each item is a combination of the original item in the parameter value set with the item in the observables array. Example 2 (zip) has a 5x1 parameter value set and a 5x1 observables array. The output is a 5x1 array where each item is a combination of the nth item in the parameter value set with the nth item in the observables array. Example 3 (outer/product) has a 1x6 parameter value set and a 4x1 observables array. Their combination results in a 4x6 array that is created by combining each item in the parameter value set with every item in the observables array, and thus each parameter value becomes an entire column in the output. Example 4 (Standard nd generalization) has a 3x6 parameter value set array and two 3x1 observables array. These combine to create two 3x6 output arrays in a similar manner to the previous example.
# Broadcast single observable
parameter_values = np.random.uniform(size=(5,)) # shape (5,)
observables = SparsePauliOp("ZZZ") # shape ()
# >> pub result has shape (5,)
# Zip
parameter_values = np.random.uniform(size=(5,)) # shape (5,)
observables = [
SparsePauliOp(pauli) for pauli in ["III", "XXX", "YYY", "ZZZ", "XYZ"]
] # shape (5,)
# >> pub result has shape (5,)
# Outer/Product
parameter_values = np.random.uniform(size=(1, 6)) # shape (1, 6)
observables = [
[SparsePauliOp(pauli)] for pauli in ["III", "XXX", "YYY", "ZZZ"]
] # shape (4, 1)
# >> pub result has shape (4, 6)
# Standard nd generalization
parameter_values = np.random.uniform(size=(3, 6)) # shape (3, 6)
observables = [
[
[SparsePauliOp(["XII"])],
[SparsePauliOp(["IXI"])],
[SparsePauliOp(["IIX"])],
],
[
[SparsePauliOp(["ZII"])],
[SparsePauliOp(["IZI"])],
[SparsePauliOp(["IIZ"])],
],
] # shape (2, 3, 1)
Each SparsePauliOp
counts as a single element in this context, regardless of the number of Paulis contained in the SparsePauliOp
. Thus, for the purpose of these broadcasting rules, all of the following elements have the same shape:
a = SparsePauliOp("Z") # shape ()
b = SparsePauliOp("IIIIZXYIZ") # shape ()
c = SparsePauliOp.from_list(["XX", "XY", "IZ"]) # shape ()
The following lists of operators, while equivalent in terms of information contained, have different shapes:
list1 = SparsePauliOp.from_list(["XX", "XY", "IZ"]) # shape ()
list2 = [SparsePauliOp("XX"), SparsePauliOp("XY"), SparsePauliOp("IZ")] # shape (3, )
Overview of primitive results
Once one or more PUBs are sent to a QPU for execution and a job successfully completes, the data is returned as a PrimitiveResult
container object accessed by calling the RuntimeJobV2.result()
method. The PrimitiveResult
contains an iterable list of PubResult
objects that contain the execution results for each PUB. Depending on the primitive used, these data will be either expectation values and their error bars in the case of the Estimator, or samples of the circuit output in the case of the Sampler.
Each element of this list corresponds to each PUB submitted to the primitive's run()
method (for example, a job submitted with 20 PUBs will return a PrimitiveResult
object that contains a list of 20 PubResults
, one corresponding to each PUB).
Each of these PubResult
objects possess both a data
and a metadata
attribute. The data
attribute is a customized DataBin
that contains the actual measurement values, standard deviations, and so forth. This DataBin
has various attributes depending on the shape or structure of the associated PUB as well as the error mitigation options specified by the primitive used to submit the job (for example, ZNE or PEC). Meanwhile, the metadata
attribute contains information about the runtime and error mitigation options used (explained later in the Result metadata section of this page).
Put simply, a single job returns a PrimitiveResult
object and contains a list of one or more PubResults
. These PubResults
are where the measurement data is stored for each of the PUBs that were submitted to the job.
Estimator output
Each PubResult
for the Estimator primitive contains at least an array of expectation values (PubResult.data.evs
) and associated standard deviations (either PubResult.data.stds
or PubResult.data.ensemble_standard_error
depending on the resilience_level
used), but can contain more data depending on the error mitigation options that were specified.
The below code snippet describes the PrimitiveResult
(and associated PubResult
) format for the job created above.
print(
f"The result of the submitted job had {len(result)} PUB and has a value:\n {result}\n"
)
print(
f"The associated PubResult of this job has the following DataBins:\n {result[0].data}\n"
)
print(f"And this DataBin has attributes: {result[0].data.keys()}")
print(
"Recall that this shape is due to our array of parameter binding sets having shape (100,), combined with \n\
our array of observables having shape (3, 1), where 2 is the number of parameters in the circuit.\n"
)
print(
f"The expectation values measured from this PUB are: \n{result[0].data.evs}"
)
Output:
The result of the submitted job had 1 PUB and has a value:
PrimitiveResult([PubResult(data=DataBin(evs=np.ndarray(<shape=(3, 100), dtype=float64>), stds=np.ndarray(<shape=(3, 100), dtype=float64>), ensemble_standard_error=np.ndarray(<shape=(3, 100), dtype=float64>), shape=(3, 100)), metadata={'shots': 4096, 'target_precision': 0.015625, 'circuit_metadata': {}, 'resilience': {}, 'num_randomizations': 32})], metadata={'dynamical_decoupling': {'enable': False, 'sequence_type': 'XX', 'extra_slack_distribution': 'middle', 'scheduling_method': 'alap'}, 'twirling': {'enable_gates': False, 'enable_measure': True, 'num_randomizations': 'auto', 'shots_per_randomization': 'auto', 'interleave_randomizations': True, 'strategy': 'active-accum'}, 'resilience': {'measure_mitigation': True, 'zne_mitigation': False, 'pec_mitigation': False}, 'version': 2})
The associated PubResult of this job has the following DataBins:
DataBin(evs=np.ndarray(<shape=(3, 100), dtype=float64>), stds=np.ndarray(<shape=(3, 100), dtype=float64>), ensemble_standard_error=np.ndarray(<shape=(3, 100), dtype=float64>), shape=(3, 100))
And this DataBin has attributes: dict_keys(['evs', 'stds', 'ensemble_standard_error'])
Recall that this shape is due to our array of parameter binding sets having shape (100,), combined with
our array of observables having shape (3, 1), where 2 is the number of parameters in the circuit.
The expectation values measured from this PUB are:
[[ 4.74202485e-02 1.49553541e-01 2.96815406e-01 4.23581720e-01
5.15922708e-01 6.03680082e-01 6.36177373e-01 6.58116979e-01
6.18964316e-01 5.86179054e-01 5.24211576e-01 4.77593230e-01
3.85264066e-01 3.14312492e-01 2.98296246e-01 2.56608866e-01
2.41147803e-01 2.62505426e-01 2.76432573e-01 3.32272275e-01
3.67210219e-01 4.03867841e-01 4.58498645e-01 4.78714107e-01
4.79853902e-01 4.71682482e-01 4.79065925e-01 4.42988186e-01
4.19616085e-01 3.44987898e-01 2.86747218e-01 2.52346853e-01
2.20721618e-01 1.96066263e-01 2.22282858e-01 2.21453104e-01
2.86195450e-01 3.50707629e-01 3.92913145e-01 4.72033775e-01
5.37100875e-01 5.61149811e-01 6.01184777e-01 6.25582903e-01
5.86854313e-01 5.25239178e-01 4.20856512e-01 3.30636152e-01
2.19593384e-01 6.86446583e-02 -9.08470110e-02 -2.50836848e-01
-3.63923785e-01 -4.80491851e-01 -5.63259141e-01 -6.17567555e-01
-6.54308992e-01 -6.42611512e-01 -6.02653531e-01 -5.60299300e-01
-4.92610777e-01 -4.17999668e-01 -3.64253006e-01 -3.11036830e-01
-2.71935928e-01 -2.53712347e-01 -2.45838093e-01 -2.59923677e-01
-3.01707485e-01 -3.42765324e-01 -3.74244472e-01 -4.59923257e-01
-4.62291918e-01 -4.91114960e-01 -5.16940063e-01 -4.99769571e-01
-4.63570443e-01 -4.38211189e-01 -3.97968391e-01 -3.37361414e-01
-2.93134588e-01 -2.51908329e-01 -2.17114107e-01 -2.13117730e-01
-2.12087238e-01 -2.33868934e-01 -3.02573235e-01 -3.48802453e-01
-4.17814169e-01 -5.10408445e-01 -5.50428697e-01 -5.99147965e-01
-6.18675032e-01 -6.16544419e-01 -5.76450598e-01 -4.84461427e-01
-4.05591458e-01 -2.85532277e-01 -1.26154640e-01 -1.46334107e-02]
[ 9.38494168e-02 9.54400848e-02 1.51113468e-01 2.08907741e-01
2.97454931e-01 3.59490986e-01 4.06150583e-01 4.93637328e-01
5.01060445e-01 5.66808059e-01 6.03923648e-01 6.86108165e-01
7.11558855e-01 7.39130435e-01 8.17603393e-01 8.30858961e-01
8.73276776e-01 9.05090138e-01 9.06680806e-01 9.54931071e-01
9.77730647e-01 9.69777306e-01 9.73488865e-01 9.93107105e-01
9.82502651e-01 9.75079533e-01 9.96288441e-01 9.84093319e-01
9.74019088e-01 9.42205726e-01 9.11452810e-01 9.05090138e-01
8.77518558e-01 8.28207847e-01 8.19194062e-01 7.63520679e-01
7.58218452e-01 7.00424178e-01 6.27253446e-01 5.84305408e-01
5.43478261e-01 4.68186638e-01 4.11983033e-01 3.70095440e-01
2.99575822e-01 2.33828208e-01 1.55885472e-01 1.24602333e-01
5.51431601e-02 7.95334040e-03 -7.31707317e-02 -1.24072110e-01
-1.80275716e-01 -2.44432662e-01 -3.05408271e-01 -3.67444327e-01
-4.45387063e-01 -4.96818664e-01 -5.17497349e-01 -6.01272534e-01
-6.45281018e-01 -6.67020148e-01 -7.43372216e-01 -7.67762460e-01
-8.29798515e-01 -8.48356310e-01 -8.72746554e-01 -9.01908802e-01
-9.29480382e-01 -9.57582185e-01 -9.65535525e-01 -9.86744433e-01
-9.90986214e-01 -1.00106045e+00 -9.95227996e-01 -1.00053022e+00
-9.84623542e-01 -9.81972428e-01 -9.78791092e-01 -9.66595970e-01
-9.40084836e-01 -8.99257688e-01 -8.73276776e-01 -8.41993637e-01
-7.95334040e-01 -7.49204666e-01 -7.21102863e-01 -6.64899258e-01
-6.00742312e-01 -5.75821845e-01 -4.88865323e-01 -4.40615058e-01
-3.78579003e-01 -3.36161188e-01 -2.69353128e-01 -1.83987275e-01
-1.43690350e-01 -8.64262990e-02 6.36267232e-03 2.22693531e-02]
[ 9.91080278e-04 2.03666997e-01 4.42517344e-01 6.38255699e-01
7.34390486e-01 8.47869177e-01 8.66204163e-01 8.22596630e-01
7.36868186e-01 6.05550050e-01 4.44499504e-01 2.69078295e-01
5.89692765e-02 -1.10505451e-01 -2.21010902e-01 -3.17641229e-01
-3.90981169e-01 -3.80079286e-01 -3.53815659e-01 -2.90386521e-01
-2.43310208e-01 -1.62041625e-01 -5.64915758e-02 -3.56788900e-02
-2.27948464e-02 -3.17145689e-02 -3.81565907e-02 -9.81169475e-02
-1.34786918e-01 -2.52229931e-01 -3.37958375e-01 -4.00396432e-01
-4.36075322e-01 -4.36075322e-01 -3.74628345e-01 -3.20614470e-01
-1.85827552e-01 9.91080278e-04 1.58572844e-01 3.59762141e-01
5.30723489e-01 6.54112983e-01 7.90386521e-01 8.81070367e-01
8.74132805e-01 8.16650149e-01 6.85827552e-01 5.36669970e-01
3.84043608e-01 1.29335976e-01 -1.08523290e-01 -3.77601586e-01
-5.47571853e-01 -7.16551041e-01 -8.21110010e-01 -8.67690783e-01
-8.63230922e-01 -7.88404361e-01 -6.87809713e-01 -5.19326065e-01
-3.39940535e-01 -1.68979187e-01 1.48662042e-02 1.45688801e-01
2.85926660e-01 3.40931615e-01 3.81070367e-01 3.82061447e-01
3.26065411e-01 2.72051536e-01 2.17046581e-01 6.68979187e-02
6.64023786e-02 1.88305253e-02 -3.86521308e-02 9.91080278e-04
5.74826561e-02 1.05550050e-01 1.82854311e-01 2.91873142e-01
3.53815659e-01 3.95441031e-01 4.39048563e-01 4.15758176e-01
3.71159564e-01 2.81466799e-01 1.15956392e-01 -3.27056492e-02
-2.34886026e-01 -4.44995045e-01 -6.11992071e-01 -7.57680872e-01
-8.58771060e-01 -8.96927651e-01 -8.83548067e-01 -7.84935580e-01
-6.67492567e-01 -4.84638256e-01 -2.58671952e-01 -5.15361744e-02]]
How the Estimator calculates error
In addition to the estimate of the mean of the observables passed in the input PUBs (the evs
field of the DataBin
), the Estimator also attempts to deliver an estimate of the error associated with those expectation values. All estimator queries will populate the stds
field with a quantity like the standard error of the mean for each expectation value, but some error mitigation options produce additional information, such as ensemble_standard_error
.
Consider a single observable . In the absence of ZNE, you can think of each shot of the Estimator execution as providing a point estimate of the expectation value . If the pointwise estimates are in a vector Os
, then the value returned in ensemble_standard_error
is equivalent to the following (in which is the standard deviation of the expectation value estimate and is the number of shots):
which treats all shots as part of a single ensemble. If you requested gate twirling (twirling.enable_gates = True
), you can sort the pointwise estimates of into sets that share a common twirl. Call these sets of estimates O_twirls
, and there are num_randomizations
(number of twirls) of them. Then stds
is the standard error of the mean of O_twirls
, as in
where is the standard deviation of O_twirls
and is the number of twirls. When you do not enable twirling, stds
and ensemble_standard_error
are equal.
If you enable ZNE, then the stds
described above become weights in a non-linear regression to an extrapolator model. What finally gets returned in the stds
in this case is the uncertainty of the fit model evaluated at a noise factor of zero. When there is a poor fit, or large uncertainty in the fit, the reported stds
can become very large. When ZNE is enabled, pub_result.data.evs_noise_factors
and pub_result.data.stds_noise_factors
are also populated, so that you can do your own extrapolation.
Sampler output
The Sampler primitive outputs job results in a similar format, with the exception that each DataBin
will contain one or more BitArray
objects which store the samples of the circuit attached to a particular ClassicalRegister
, typically one bitstring per shot. The attribute label for each bit array object depends on the ClassicalRegisters
defined in the circuit being executed. The measurement data from these BitArrays
can then be processed into a dictionary with key-value pairs corresponding to each bitstring measured (for example, '1011001') and the number of times (or counts) it was measured.
For example, a circuit that has measurement instructions added by the QuantumCircuit.measure_all()
function possesses a classical register with the label 'meas'. After execution, a count data dictionary can be created by executing:
# Add measurement instructions to the example circuit
circuit.measure_all()
# Transpile the circuit
pm = generate_preset_pass_manager(optimization_level=1, backend=backend)
transpiled_circuit = pm.run(circuit)
# Create a PUB for the Sampler primitive using the same parameters defined earlier
sampler_pub = (transpiled_circuit, params)
sampler = Sampler(mode=backend)
job = sampler.run([sampler_pub])
result = job.result()
print(
f"The result of the submitted job had {len(result)} PUB and has a value:\n {result}\n"
)
print(
f"The associated PubResult of this Sampler job has the following DataBins:\n {result[0].data}\n"
)
print(f"It has a key-value pair dict: \n{result[0].data.items()}\n")
print(
f"And the raw data can be converted to a bitstring-count format: \n{result[0].data.meas.get_counts()}"
)
Output:
The result of the submitted job had 1 PUB and has a value:
PrimitiveResult([SamplerPubResult(data=DataBin(meas=BitArray(<shape=(100,), num_shots=4096, num_bits=2>), shape=(100,)), metadata={'circuit_metadata': {}})], metadata={'execution': {'execution_spans': ExecutionSpans([SliceSpan(<start='2024-12-15 08:39:29', stop='2024-12-15 08:44:16', size=409600>)])}, 'version': 2})
The associated PubResult of this Sampler job has the following DataBins:
DataBin(meas=BitArray(<shape=(100,), num_shots=4096, num_bits=2>), shape=(100,))
It has a key-value pair dict:
dict_items([('meas', BitArray(<shape=(100,), num_shots=4096, num_bits=2>))])
And the raw data can be converted to a bitstring-count format:
{'11': 104811, '01': 101782, '00': 101894, '10': 101113}
Result metadata
In addition to the execution results, both the PrimitiveResult
and PubResult
objects contain a metadata attribute about the job that was submitted. The metadata containing information for all submitted PUBs (such as the various runtime options available) can be found in the PrimitiveResult.metatada
, while the metadata specific to each PUB is found in PubResult.metadata
.
# Print out the results metadata
print("The metadata of the PrimitiveResult is:")
for key, val in result.metadata.items():
print(f"'{key}' : {val},")
print("\nThe metadata of the PubResult result is:")
for key, val in result[0].metadata.items():
print(f"'{key}' : {val},")
Output:
The metadata of the PrimitiveResult is:
'execution' : {'execution_spans': ExecutionSpans([SliceSpan(<start='2024-12-15 08:39:29', stop='2024-12-15 08:44:16', size=409600>)])},
'version' : 2,
The metadata of the PubResult result is:
'circuit_metadata' : {},
For Sampler jobs, you can also review the result metadata to understand when certain data was run; this is called the execution span.