Skip to main contentIBM Quantum Documentation Mirror

Primitive inputs and outputs

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.

[1] :
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.

This image illustrates several visual representations of array broadcasting
Visual representation of broadcasting
[2] :
# 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.

[3] :
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: 
[[-8.60294118e-03  2.06519608e-01  3.71617647e-01  5.27083333e-01
   7.15147059e-01  7.13455882e-01  7.96715686e-01  8.08357843e-01
   8.68970588e-01  7.94338235e-01  7.20686275e-01  6.04558824e-01
   5.45637255e-01  4.83112745e-01  4.17769608e-01  3.24607843e-01
   3.54926471e-01  3.81421569e-01  3.91151961e-01  4.00098039e-01
   4.97549020e-01  5.20637255e-01  6.37696078e-01  6.33333333e-01
   6.14754902e-01  6.30147059e-01  5.70318627e-01  5.96470588e-01
   5.98823529e-01  4.77009804e-01  3.99583333e-01  3.20931373e-01
   2.40269608e-01  1.76127451e-01  2.61029412e-01  3.04313725e-01
   3.21397059e-01  3.97132353e-01  4.38014706e-01  5.47524510e-01
   5.62892157e-01  6.84730392e-01  7.47132353e-01  7.85098039e-01
   6.81200980e-01  7.17009804e-01  4.90147059e-01  4.07794118e-01
   2.80147059e-01  5.82598039e-02 -8.69362745e-02 -3.56985294e-01
  -4.88872549e-01 -6.36151961e-01 -7.07941176e-01 -8.37696078e-01
  -8.10710784e-01 -8.14387255e-01 -7.61053922e-01 -7.40563725e-01
  -7.02328431e-01 -6.15147059e-01 -5.00441176e-01 -4.72279412e-01
  -4.73970588e-01 -3.63921569e-01 -4.18897059e-01 -4.48137255e-01
  -4.77916667e-01 -5.56151961e-01 -5.99926471e-01 -6.01617647e-01
  -6.70245098e-01 -7.41151961e-01 -7.32843137e-01 -6.53406863e-01
  -6.87500000e-01 -6.68700980e-01 -5.25686275e-01 -4.63063725e-01
  -3.61740196e-01 -3.14656863e-01 -2.97720588e-01 -2.38480392e-01
  -2.49877451e-01 -3.60637255e-01 -3.69950980e-01 -4.40906863e-01
  -5.86666667e-01 -6.41740196e-01 -7.56250000e-01 -8.24828431e-01
  -8.24264706e-01 -8.64705882e-01 -7.54730392e-01 -6.80465686e-01
  -5.69117647e-01 -4.18602941e-01 -2.43602941e-01 -9.44362745e-02]
 [ 1.17647059e-03  1.45882353e-01  1.91764706e-01  2.88235294e-01
   5.55294118e-01  4.89411765e-01  5.81176471e-01  6.69411765e-01
   8.77647059e-01  8.71764706e-01  9.36470588e-01  9.51764706e-01
   1.01529412e+00  1.10470588e+00  1.12352941e+00  1.18352941e+00
   1.19882353e+00  1.28000000e+00  1.28352941e+00  1.26588235e+00
   1.32352941e+00  1.30352941e+00  1.36117647e+00  1.36470588e+00
   1.28588235e+00  1.31176471e+00  1.33058824e+00  1.39882353e+00
   1.37411765e+00  1.30941176e+00  1.23176471e+00  1.18352941e+00
   1.08470588e+00  9.87058824e-01  9.70588235e-01  9.51764706e-01
   8.96470588e-01  8.20000000e-01  7.10588235e-01  6.89411765e-01
   5.69411765e-01  5.74117647e-01  6.08235294e-01  6.09411765e-01
   3.61176471e-01  4.36470588e-01  2.37647059e-01  2.20000000e-01
   1.41176471e-01  2.70588235e-02 -3.29411765e-02 -2.47058824e-01
  -3.87058824e-01 -4.94117647e-01 -4.89411765e-01 -7.02352941e-01
  -7.32941176e-01 -8.21176471e-01 -9.10588235e-01 -1.01176471e+00
  -1.11176471e+00 -1.14941176e+00 -1.15529412e+00 -1.15411765e+00
  -1.30823529e+00 -1.14941176e+00 -1.30470588e+00 -1.31294118e+00
  -1.35411765e+00 -1.39294118e+00 -1.40941176e+00 -1.38705882e+00
  -1.41647059e+00 -1.48352941e+00 -1.47058824e+00 -1.43058824e+00
  -1.44117647e+00 -1.43176471e+00 -1.41411765e+00 -1.36117647e+00
  -1.25411765e+00 -1.24941176e+00 -1.20941176e+00 -1.11176471e+00
  -1.00588235e+00 -1.07176471e+00 -1.00705882e+00 -8.36470588e-01
  -8.69411765e-01 -7.55294118e-01 -7.58823529e-01 -7.31764706e-01
  -6.11764706e-01 -6.41176471e-01 -4.49411765e-01 -4.84705882e-01
  -2.70588235e-01 -2.60000000e-01 -1.60000000e-01 -1.72941176e-01]
 [-1.83823529e-02  2.67156863e-01  5.51470588e-01  7.65931373e-01
   8.75000000e-01  9.37500000e-01  1.01225490e+00  9.47303922e-01
   8.60294118e-01  7.16911765e-01  5.04901961e-01  2.57352941e-01
   7.59803922e-02 -1.38480392e-01 -2.87990196e-01 -5.34313725e-01
  -4.88970588e-01 -5.17156863e-01 -5.01225490e-01 -4.65686275e-01
  -3.28431373e-01 -2.62254902e-01 -8.57843137e-02 -9.80392157e-02
  -5.63725490e-02 -5.14705882e-02 -1.89950980e-01 -2.05882353e-01
  -1.76470588e-01 -3.55392157e-01 -4.32598039e-01 -5.41666667e-01
  -6.04166667e-01 -6.34803922e-01 -4.48529412e-01 -3.43137255e-01
  -2.53676471e-01 -2.57352941e-02  1.65441176e-01  4.05637255e-01
   5.56372549e-01  7.95343137e-01  8.86029412e-01  9.60784314e-01
   1.00122549e+00  9.97549020e-01  7.42647059e-01  5.95588235e-01
   4.19117647e-01  8.94607843e-02 -1.40931373e-01 -4.66911765e-01
  -5.90686275e-01 -7.78186275e-01 -9.26470588e-01 -9.73039216e-01
  -8.88480392e-01 -8.07598039e-01 -6.11519608e-01 -4.69362745e-01
  -2.92892157e-01 -8.08823529e-02  1.54411765e-01  2.09558824e-01
   3.60294118e-01  4.21568627e-01  4.66911765e-01  4.16666667e-01
   3.98284314e-01  2.80637255e-01  2.09558824e-01  1.83823529e-01
   7.59803922e-02  1.22549020e-03  4.90196078e-03  1.23774510e-01
   6.61764706e-02  9.43627451e-02  3.62745098e-01  4.35049020e-01
   5.30637255e-01  6.20098039e-01  6.13970588e-01  6.34803922e-01
   5.06127451e-01  3.50490196e-01  2.67156863e-01 -4.53431373e-02
  -3.03921569e-01 -5.28186275e-01 -7.53676471e-01 -9.17892157e-01
  -1.03676471e+00 -1.08823529e+00 -1.06004902e+00 -8.76225490e-01
  -8.67647059e-01 -5.77205882e-01 -3.27205882e-01 -1.59313725e-02]]

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:

[4] :
# 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()
[5] :
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': 119117, '01': 90745, '10': 101002, '00': 98736}

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.

[6] :
# 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:
'version' : 2,

The metadata of the PubResult result is:
'circuit_metadata' : {},