Primitive inputs and outputs
This page gives an overview of the inputs and outputs of the Qiskit Runtime V2 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,
QiskitRuntimeService,
)
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit.quantum_info import Pauli, 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(opens in a new tab).
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(f'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': 8192, 'target_precision': 0.015625, 'circuit_metadata': {}, 'resilience': {}, 'num_randomizations': 64})], 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:
[[-0.1253276 -0.02711811 0.15850089 0.25400904 0.358169 0.44055176
0.43474898 0.57536626 0.55459335 0.55629578 0.52672338 0.47779854
0.41996413 0.42307899 0.38785687 0.33925426 0.39231703 0.37139105
0.34996026 0.35689889 0.4612656 0.46612586 0.52343398 0.56602168
0.57885169 0.58767803 0.60378402 0.60561803 0.57027239 0.57247159
0.59607742 0.50760188 0.47214346 0.47415201 0.41861883 0.44952847
0.43219533 0.44040676 0.40249941 0.48040858 0.5679443 0.59436693
0.55982417 0.53112715 0.60474802 0.50413793 0.4190055 0.40432805
0.32332012 0.08527207 0.02348499 -0.04901882 -0.09975081 -0.30863193
-0.37666753 -0.38527905 -0.39232508 -0.5119788 -0.53687354 -0.53561685
-0.47661167 -0.41843892 -0.45587367 -0.40774903 -0.36241971 -0.39365964
-0.38070611 -0.41234882 -0.38852817 -0.43184894 -0.50237374 -0.51781111
-0.55595744 -0.5583097 -0.58454437 -0.61667848 -0.56125271 -0.59292496
-0.52196784 -0.49473964 -0.56176291 -0.41409959 -0.40781079 -0.37921044
-0.419078 -0.40519806 -0.40361915 -0.45760832 -0.44122575 -0.51825149
-0.5399347 -0.54930077 -0.61266407 -0.52275998 -0.58784989 -0.46842173
-0.43105411 -0.33410399 -0.23594552 -0.09199856]
[-0.28107345 -0.24435028 0.00141243 0.05649718 0.14124294 0.3079096
0.22881356 0.49293785 0.56355932 0.65536723 0.72740113 0.77118644
0.78954802 0.88418079 0.94491525 0.92090395 1.05649718 1.05932203
1.01836158 1.00847458 1.14971751 1.12711864 1.16949153 1.20903955
1.15960452 1.15254237 1.16384181 1.1779661 1.21468927 1.2019774
1.28531073 1.20056497 1.16101695 1.13841808 1.02259887 1.06920904
0.96610169 0.88841808 0.76412429 0.8220339 0.85451977 0.79519774
0.61299435 0.55084746 0.66101695 0.42937853 0.39124294 0.42937853
0.32344633 0.10875706 0.10875706 0.06355932 0.08757062 -0.16384181
-0.19915254 -0.23728814 -0.20480226 -0.52966102 -0.59180791 -0.70621469
-0.67090395 -0.71045198 -0.88418079 -0.90960452 -0.89689266 -1.0240113
-1.04943503 -1.09180791 -1.05367232 -1.08898305 -1.20056497 -1.15254237
-1.17655367 -1.23163842 -1.21186441 -1.30084746 -1.16242938 -1.24858757
-1.1779661 -1.15677966 -1.30508475 -1.07344633 -1.04661017 -1.01412429
-0.9759887 -0.94632768 -0.87853107 -0.81920904 -0.71610169 -0.75988701
-0.69774011 -0.62711864 -0.64548023 -0.51129944 -0.56638418 -0.3940678
-0.45621469 -0.35451977 -0.25706215 -0.19350282]
[ 0.03041825 0.19011407 0.31558935 0.45152091 0.57509506 0.57319392
0.64068441 0.65779468 0.54562738 0.45722433 0.32604563 0.18441065
0.05038023 -0.03802281 -0.16920152 -0.24239544 -0.27186312 -0.31653992
-0.31844106 -0.29467681 -0.22718631 -0.19486692 -0.12262357 -0.0769962
-0.00190114 0.02281369 0.04372624 0.03326996 -0.07414449 -0.05703422
-0.09315589 -0.18536122 -0.21673004 -0.19011407 -0.18536122 -0.17015209
-0.10171103 -0.00760456 0.04087452 0.13878327 0.28136882 0.39353612
0.50665399 0.51140684 0.54847909 0.57889734 0.44676806 0.37927757
0.32319392 0.06178707 -0.06178707 -0.16159696 -0.28707224 -0.45342205
-0.55418251 -0.53326996 -0.57984791 -0.49429658 -0.48193916 -0.36501901
-0.28231939 -0.12642586 -0.02756654 0.09410646 0.17205323 0.23669202
0.28802281 0.26711027 0.27661597 0.22528517 0.19581749 0.11692015
0.06463878 0.11501901 0.04277567 0.06749049 0.03992395 0.06273764
0.13403042 0.16730038 0.18155894 0.24524715 0.23098859 0.25570342
0.1378327 0.13593156 0.07129278 -0.0960076 -0.16634981 -0.27661597
-0.38212928 -0.47148289 -0.57984791 -0.53422053 -0.60931559 -0.54277567
-0.40589354 -0.31368821 -0.2148289 0.0095057 ]]
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([PubResult(data=DataBin(meas=BitArray(<shape=(100,), num_shots=4096, num_bits=2>), shape=(100,)), metadata={'circuit_metadata': {}})], metadata={'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': 115808, '10': 104963, '01': 89334, '00': 99495}
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(f'The metadata of the PrimitiveResult is:')
for key, val in result.metadata.items():
print(f"'{key}' : {val},")
print(f'\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:
'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 metadata of the PubResult result is:
'shots' : 8192,
'target_precision' : 0.015625,
'circuit_metadata' : {},
'resilience' : {},
'num_randomizations' : 64,