Skip to main contentIBM Quantum Documentation Preview
This is a preview build of IBM Quantum™ documentation. Refer to docs.quantum.ibm.com for the official documentation.

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.2.4
qiskit-aer~=0.15.1
qiskit-ibm-runtime~=0.33.2
qiskit-serverless~=0.17.1
qiskit-ibm-catalog~=0.1
qiskit-addon-sqd~=0.7.0
qiskit-addon-utils~=0.1.0
qiskit-addon-aqc-tensor~=0.1.1
scipy~=1.14.1
qiskit-addon-obp~=0.1.0
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 more Parameter 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 as Pauli, SparsePauliOp, PauliList, or str.
  • 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 to None) if the circuit has no Parameter 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 more Parameter 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 θk\theta_k (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.

This image illustrates several visual representations of array broadcasting
Visual representation of broadcasting
# 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)
SparsePauliOp

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: 
[[ 0.03525966  0.18221849  0.34426107  0.46601598  0.56624996  0.62528592
   0.65986203  0.67647733  0.65033187  0.58429132  0.53950098  0.45532527
   0.41670659  0.34737847  0.30121012  0.2777565   0.26360572  0.26449996
   0.3029334   0.3263005   0.37274425  0.42511491  0.4485189   0.48809133
   0.48262218  0.48347252  0.46466941  0.42570025  0.37335037  0.31289666
   0.26540512  0.21130494  0.17736846  0.15846428  0.17792834  0.2136133
   0.25563101  0.32014521  0.37919026  0.47307929  0.51674624  0.58956172
   0.62853425  0.61837927  0.59136087  0.5308765   0.43394801  0.33814007
   0.17136437  0.02259054 -0.12731473 -0.26254675 -0.39515449 -0.52460221
  -0.58534171 -0.64491858 -0.6584131  -0.65045424 -0.61197871 -0.5620102
  -0.48247981 -0.41558605 -0.36313926 -0.32453617 -0.27417042 -0.25355413
  -0.27131932 -0.28880106 -0.32102127 -0.36899137 -0.4109462  -0.46217268
  -0.49454644 -0.51388527 -0.4960081  -0.49814058 -0.43987936 -0.38881681
  -0.34910643 -0.291628   -0.21428542 -0.19210407 -0.16773308 -0.16163988
  -0.1730861  -0.23503031 -0.24502344 -0.35295362 -0.40187148 -0.49512606
  -0.55987175 -0.60525497 -0.63451886 -0.61865518 -0.57594405 -0.49683844
  -0.39181132 -0.26956226 -0.10402427  0.02904929]
 [ 0.09423275  0.13285273  0.21627188  0.28218332  0.34037075  0.39083419
   0.4423275   0.51390319  0.54788877  0.57826982  0.63954686  0.69773429
   0.74562307  0.80020597  0.82492276  0.85066941  0.87332647  0.91194645
   0.92070031  0.96138002  0.96395469  0.97888774  0.97322348  0.99485067
   0.97785788  0.98712667  0.97373841  0.96189495  0.94902163  0.9330587
   0.90164779  0.89031926  0.85221421  0.8038105   0.78269825  0.74407827
   0.70803296  0.65139032  0.57775489  0.55715757  0.48455201  0.45056643
   0.38774459  0.30638517  0.253862    0.18486097  0.1292482   0.10968074
   0.00720906 -0.06127703 -0.1168898  -0.16838311 -0.23480947 -0.3130793
  -0.35736354 -0.41143151 -0.47373841 -0.53501545 -0.57209063 -0.64521112
  -0.66374871 -0.70957775 -0.76210093 -0.8115345  -0.82028836 -0.85221421
  -0.88774459 -0.92018538 -0.93820803 -0.96704428 -0.97476828 -0.97631308
  -0.98455201 -1.00102987 -0.97940268 -0.9907312  -0.96704428 -0.95674562
  -0.94644696 -0.92533471 -0.88568486 -0.86251287 -0.82234809 -0.79351184
  -0.75283213 -0.7415036  -0.63182286 -0.6277034  -0.55046344 -0.51699279
  -0.45829042 -0.40576725 -0.35581874 -0.28372812 -0.22605561 -0.16168898
  -0.10350154 -0.03861998  0.04119464  0.07878476]
 [-0.02371342  0.23158426  0.47225025  0.64984864  0.79212916  0.85973764
   0.87739657  0.83905146  0.75277497  0.59031282  0.4394551   0.21291625
   0.08779011 -0.10544904 -0.22250252 -0.29515641 -0.34611504 -0.38294652
  -0.3148335  -0.30877901 -0.2184662  -0.12865792 -0.07618567 -0.01866801
  -0.01261352 -0.02018163 -0.0443996  -0.11049445 -0.20232089 -0.30726539
  -0.37083754 -0.46770938 -0.4974773  -0.48688194 -0.42684157 -0.31685166
  -0.19677094 -0.0110999   0.18062563  0.38900101  0.54894046  0.72855701
   0.86932392  0.93037336  0.92885974  0.87689203  0.73864783  0.56659939
   0.33551968  0.10645812 -0.13773966 -0.35671039 -0.5554995  -0.73612513
  -0.81331988 -0.87840565 -0.84308779 -0.76589304 -0.6518668  -0.47880928
  -0.3012109  -0.12159435  0.0358224   0.16246216  0.27194753  0.34510595
   0.34510595  0.34258325  0.29616549  0.22906155  0.15287588  0.05196771
  -0.00454087 -0.02674067 -0.01261352 -0.00554995  0.08728557  0.17911201
   0.24823411  0.34207871  0.45711403  0.47830474  0.48688194  0.47023209
   0.40665994  0.27144299  0.14177598 -0.07820383 -0.25327952 -0.47325933
  -0.66145308 -0.80474268 -0.91321897 -0.95358224 -0.92583249 -0.83198789
  -0.68012109 -0.50050454 -0.24924319 -0.02068618]]

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 O\mathcal{O}. In the absence of ZNE, you can think of each shot of the Estimator execution as providing a point estimate of the expectation value O\langle \mathcal{O} \rangle. If the pointwise estimates are in a vector Os, then the value returned in ensemble_standard_error is equivalent to the following (in which σO\sigma_{\mathcal{O}} is the standard deviation of the expectation value estimate and NshotsN_{shots} is the number of shots):

σONshots,\frac{ \sigma_{\mathcal{O}} }{ \sqrt{N_{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 O\langle \mathcal{O} \rangle 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

σONtwirls,\frac{ \sigma_{\mathcal{O}} }{ \sqrt{N_{twirls}} },

where σO\sigma_{\mathcal{O}} is the standard deviation of O_twirls and NtwirlsN_{twirls} 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-11-15 09:06:56', stop='2024-11-15 09:09:21', 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': 106602, '00': 100662, '10': 100359, '01': 101977}

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-11-15 09:06:56', stop='2024-11-15 09:09:21', 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.