# Configure error mitigation for Qiskit Runtime

Error mitigation techniques allow users to mitigate circuit errors by modeling the device noise at the time of execution. This typically results in quantum pre-processing overhead related to model training and classical post-processing overhead to mitigate errors in the raw results by using the generated model.

The error mitigation techniques built in to primitives are advanced
resilience options. To specify these options, use the `resilience_level`

option when submitting your job.

The resilience level specifies how much resilience to build against errors. Higher levels generate more accurate results, at the expense of longer processing times. Resilience levels can be used to configure the cost/accuracy trade-off when applying error mitigation to your primitive query. Error mitigation reduces errors (bias) in results by processing the outputs from a collection, or ensemble, of related circuits. The degree of error reduction depends on the method applied. The resilience level abstracts the detailed choice of error mitigation method to allow users to reason about the cost/accuracy trade that is appropriate to their application.

Given this, each level corresponds to a method or methods with increasing level of quantum sampling overhead to enable you experiment with different time-accuracy tradeoffs. The following table shows you which levels and corresponding methods are available for each of the primitives.

Error mitigation is task specific so the techniques you are able to apply vary based whether you are sampling a distribution or generating expectation values.

To ensure faster and more efficient results, as of 1 March 2024, circuits and observables need to be transformed to only use instructions supported by the system (referred to as *instruction set architecture (ISA)* circuits and observables) before being submitted to the Qiskit Runtime primitives. See the transpilation documentation for instructions to transform circuits. Due to this change, the primitives will no longer perform layout or routing operations. Consequently, transpilation options referring to those tasks will no longer have any effect. By default, all primitives except Sampler V2 still optimize the input circuits. To bypass all optimization, set `optimization_level=0`

.

*Exception*: When you initialize the Qiskit Runtime Service with the Q-CTRL channel strategy (example below), abstract circuits are still supported.

`service = QiskitRuntimeService(channel="ibm_cloud", channel_strategy="q-ctrl")`

In V2, Estimator supports the following resilience levels. Sampler does not support resilience levels.

Resilience Level | Definition | Technique |
---|---|---|

0 | No mitigation | None |

1 [Default] | Minimal mitigation costs: Mitigate error associated with readout errors | Twirled Readout Error eXtinction (TREX) measurement twirling |

2 | Medium mitigation costs. Typically reduces bias in estimators, but is not guaranteed to be zero-bias. | Level 1 + Zero Noise Extrapolation (ZNE) and gate twirling |

Resilience levels in V1 primitives:

Resilience Level | Definition | Estimator | Sampler |
---|---|---|---|

0 | No mitigation | None | None |

1 [Default] | Minimal mitigation costs: Mitigate error associated with readout errors | Twirled Readout Error eXtinction (TREX) | Matrix-free Measurement Mitigation (M3) |

2 | Medium mitigation costs. Typically reduces bias in estimators, but is not guaranteed to be zero-bias. | Zero Noise Extrapolation (ZNE) | - |

3 | Heavy mitigation with layer sampling. Theoretically expected to deliver zero-bias estimators. | Probabilistic Error Cancellation (PEC) | - |

Resilience levels are currently in beta so sampling overhead and solution quality will vary from circuit to circuit. New features, advanced options, and management tools will be released on a rolling basis. Specific error mitigation methods are not guaranteed to be applied at each resilience level.

If using an IBM Cloud® Qiskit Runtime service instance with Q-CTRL performance management enabled, there is no need to specify runtime optimization or resilience levels, as the strategy includes an automatic preset.

Setting `optimization_level`

or `resilience_level`

equal to 0 will result in an
execution error. Levels 1, 2, and 3 are permitted but will not impact performance.
Setting other options will likewise not impact performance, and it may result in a
runtime warning. For more information visit the Q-CTRL documentation(opens in a new tab).

## Configure Estimator V2 with resilience levels

You can use resilience levels to specify error mitigation techniques, or you can set custom techniques individually as described in Custom error settings with Estimator V2. You cannot specify resilience levels in Sampler V2. However, you can set custom techniques individually.

## Resilience Level 0

No error mitigation is applied to the user program.

## Resilience Level 1

Level 1 applies **readout error mitigation** and **measurement twirling** by applying a model-free technique known
as Twirled Readout Error eXtinction (TREX). It reduces measurement error
by diagonalizing the noise channel associated with measurement by
randomly flipping qubits through X gates immediately before measurement. A
rescaling term from the diagonal noise channel is learned by
benchmarking random circuits initialized in the zero state. This allows
the service to remove bias from expectation values that result from
readout noise. This approach is described further in Model-free
readout-error mitigation for quantum expectation
values(opens in a new tab).

## Resilience Level 2

Level 2 applies the **error mitigation techniques included in level 1** and also applies **gate twirling** and uses the **Zero Noise Extrapolation method (ZNE)**. ZNE computes an
expectation value of the observable for different noise factors
(amplification stage) and then uses the measured expectation values to
infer the ideal expectation value at the zero-noise limit (extrapolation
stage). This approach tends to reduce errors in expectation values, but
is not guaranteed to produce an unbiased result.

The overhead of this method scales with the number of noise factors. The default settings sample the expectation value at three noise factors, leading to a roughly 3x overhead when employing this resilience level.

In Level 2, the TREX method randomly flips qubits through X gates immediately before measurement, and flips the corresponding measured bit if an X gate was applied. This approach is described further in Model-free readout-error mitigation for quantum expectation values(opens in a new tab).

### Example

The `Estimator`

interface lets users seamlessly work with the variety of
error mitigation methods to reduce error in expectation values of
observables. The following code uses Zero Noise Extrapolation by simply
setting `resilience_level 2`

.

```
from qiskit_ibm_runtime import QiskitRuntimeService
from qiskit_ibm_runtime import EstimatorV2 as Estimator
service = QiskitRuntimeService()
backend = service.least_busy(operational=True, simulator=False)
# Setting options during primitive initialization
estimator = Estimator(backend, options={"resilience_level": 2})
```

As you increase the resilience level, you will be able to use additional methods to improve the accuracy of your result. However, because the methods become more advanced with each level, they require additional sampling overhead (time) to generate more accurate expectation values. Note that higher resilience levels do not guarantee better quality. Higher levels only mean greater overhead. Each method has its strengths and weaknesses. For example, TREX (Twirled Readout Error eXtinction) is good for shallow circuits because of its readout error mitigation, whereas ZNE (Zero Noise Extrapolation) is good for deeper circuits. PEC can mitigate arbitrary errors but may not work in practice because of its large overhead.

## Configure Estimator (V1) with resilience levels

## Resilience Level 0

No error mitigation is applied to the user program.

## Resilience Level 1

Level 1 applies error mitigation methods that particularly address readout errors. In the Estimator, we apply a model-free technique known as Twirled Readout Error eXtinction (TREX). It reduces measurement error by diagonalizing the noise channel associated with measurement by randomly flipping qubits through X gates immediately before measurement, and flipping the corresponding measured bit if an X gate was applied. A rescaling term from the diagonal noise channel is learned by benchmarking random circuits initialized in the zero state. This allows the service to remove bias from expectation values that result from readout noise. This approach is described further in Model-free readout-error mitigation for quantum expectation values(opens in a new tab).

## Resilience Level 2

Level 2 uses the Zero Noise Extrapolation method (ZNE) which computes an expectation value of the observable for different noise factors (amplification stage) and then uses the measured expectation values to infer the ideal expectation value at the zero-noise limit (extrapolation stage). This approach tends to reduce errors in expectation values, but is not guaranteed to produce an unbiased result.

The overhead of this method scales with the number of noise factors. The default settings sample the expectation value at three noise factors, leading to a roughly 3x overhead when employing this resilience level.

## Resilience Level 3

Level 3 enables the Probabilistic Error Cancelation (PEC) method. This approach mitigates error by learning and inverting a sparse noise model that is able to capture correlated noise. PEC returns an unbiased estimate of an expectation value so long as learned noise model faithfully represents the actual noise model at the time of mitigation. In practice, the experimental procedure for learning the noise model has ambiguities due to certain error terms that cannot be independently distinguished. These are resolved by a symmetry assumption, which depending on the true underlying noise may lead a biased estimate of the mitigated expectation values due to using an imperfect noise model.

The Qiskit Runtime primitive implementation of PEC specifically
addresses noise in self-inverse two-qubit gates, so it first
*stratifies* each input circuit into an alternating sequence of
simultaneous 1-qubit gates followed by a layer of simultaneous 2-qubit
gates. Then it learns the noise model associated with each unique
2-qubit gate layer.

The overhead of this method scales with the number of noise factors. The default settings sample the expectation value at three noise factors, leading to a roughly 3x overhead when employing this resilience level.

PEC uses a quasi-probability method to mimic the effect of inverting the learned noise. This requires sampling from a randomized circuit family associated with the user's original circuit. Applying PEC will increase the variability of the returned expectation value estimates unless the number of samples per circuit is also increased for both input and characterization circuits. The amount of samples required to counter this variability scales exponentially with the noise strength of the mitigated circuit.

How this works:

When estimating an unmitigated Pauli observable $\langle P\rangle$, the standard error in the estimated expectation value is given by

$\frac{1}{\sqrt{N_{\text{shots}}}}\left(1- \langle P\rangle^2\right)$,

where $N_{\text{shots}}$ is the number of shots used to estimate $\langle P\rangle$. When applying PEC mitigation, the standard error becomes $\sqrt{\frac{S}{N_{\text{samples}}}}\left(1- \langle P\rangle^2\right)$, where $N_{\text{samples}}$ is the number of PEC samples.

The sampling overhead scales exponentially with a parameter that characterizes the collective noise of the input circuit. As the Qiskit Runtime primitive learns the noise of your circuit, it will return metadata about the sampling overhead associated with that particular layer. Let's label the overhead of layer $l$ as $\gamma_l$. Then the total sampling overhead for mitigating your circuit is the product of all the layer overheads, that is:

$S = \prod_l \gamma_l$

When the Estimator completes the model-learning phase of the primitive query, it will return metadata about the total sampling overhead for circuit.

Depending on the precision required by your application, you will need to scale the number of samples accordingly. The following plot illustrates the relationship between estimator error and number of circuit samples for different total sampling overheads.

Note that the number of samples required to deliver a desired accuracy is not known before the primitive query because the mitigation scaling factor is discovered during the learning phase of PEC.

We suggest starting with short depth circuits to get a feel for the scaling of the sampling overhead of PEC before attempting larger problems.

### Example

The Estimator interface lets users seamlessly work with the variety of
error mitigation methods to reduce error in expectation values of
observables. The following code uses Zero Noise Extrapolation by simply
setting `resilience_level=2`

.

```
from qiskit_ibm_runtime import QiskitRuntimeService, Estimator, Options
service = QiskitRuntimeService()
options = Options()
options.resilience_level = 2
options.optimization_level = 1
backend = service.least_busy(operational=True, simulator=False)
estimator = Estimator(options=options, backend=backend)
```

As you increase the resilience level, you will be able to use additional methods to improve the accuracy of your result. However, because the methods become more advanced with each level, they require additional sampling overhead (time) to generate more accurate expectation values. Note that higher resilience levels do not guarantee better quality. Higher levels only mean greater overhead. Each method has its strengths and weaknesses. For example, TREX (Twirled Readout Error eXtinction) is good for shallow circuits because of its readout error mitigation, whereas ZNE (Zero Noise Extrapolation) is good for deeper circuits. PEC can mitigate arbitrary errors but may not work in practice because of its large overhead.

## Configure Sampler (V1) with resilience levels

The Sampler V1 default resilience setting (level 1) enables readout error mitigation to allow users to generate mitigated quasi-probability distributions.

## Resilience Level 1

Level 1 uses matrix-free measurement mitigation (M3) routine to mitigate readout error. M3 works in a reduced subspace defined by the noisy input bit strings that are to be corrected. Because the number of unique bit strings can be much smaller than the dimensionality of the full multi-qubit Hilbert space, the resulting linear system of equations is nominally much easier to solve.

```
from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Options
service = QiskitRuntimeService()
options = Options()
options.resilience_level = 1
options.optimization_level = 1
backend = service.least_busy(operational=True, simulator=False)
sampler = Sampler(backend, options=options)
```

## Custom error settings (V2 primitives)

With the V2 primitives, you can turn on and off individual error mitigation and suppression methods, including dynamical decoupling, gate and measurement twirling, measurement error mitigation, and ZNE.

- Not all options are available for both primitives. See the API reference for the list of available options.
- Dynamical decoupling is not supported when the input circuits are dynamic.

```
from qiskit_ibm_runtime import QiskitRuntimeService
from qiskit_ibm_runtime import EstimatorV2 as Estimator
service = QiskitRuntimeService()
backend = service.least_busy(operational=True, simulator=False)
estimator = Estimator(backend)
options = estimator.options
# Turn on gate twirling.
options.twirling.enable_gates = True
# Turn on measurement error mitigation.
options.resilience.measure_mitigation = True
print(f">>> gate twirling is turned on: {estimator.options.twirling.enable_gates}")
print(f">>> measurement error mitigation is turned on: {estimator.options.resilience.measure_mitigation}")
```

```
from qiskit_ibm_runtime import SamplerV2 as Sampler, Options
# Estimator and Sampler now have different options
options = sampler.options
options.dynamical_decoupling.enable = True
# Turn on gate twirling. Requires qiskit_ibm_runtime 0.23.0 or later.
options.twirling.enable_gates = True
print(f">>> dynamical decoupling is turned on: {sampler.options.dynamical_decoupling.enable}")
print(f">>> gate twirling is turned on: {sampler.options.twirling.enable_gates}")
```

## Advanced resilience options (V1 primitives)

You can tune advanced options to configure your resilience strategy further. These methods can be used alongside resilience levels where you change the specific options of interest and let your previously set resilience level manage the rest.

As a part of the beta release of the resilience options, users will be able configure ZNE by using the following advanced options. We will soon add options to tune other resilience levels that include PEC.

Options | Inputs | Description |
---|---|---|

`options.resilience.noise_amplifier(Optional\[str\])` select your amplification strategy | `TwoQubitAmplifier` [Default] | Amplifies noise of all performing local gate folding. |

`CxAmplifier` | Amplifies noise of all CNOT gates by performing local gate folding. | |

`LocalFoldingAmplifier` | Amplifies noise of all gates by performing local gate folding. | |

`GlobalFoldingAmplifier` | Amplifies noise of the input circuit by performing global folding of the entire input circuit. | |

`options.resilience.noise_factors(Optional[Sequence[float]])` | (1, 3, 5)[Default] | Noise amplification factors, where [1] represents the baseline noise. They all need to be greater than or equal to the baseline. |

`options.resilience.extrapolator(Optional\[str\])` | `LinearExtrapolator` [Default] | Polynomial extrapolation of degree one. |

`Quadratic Extrapolator` | Polynomial extrapolation of degree two and lower. | |

`Cubic Extrapolator` | Polynomial extrapolation of degree three and lower. | |

`Quartic Extrapolator` | Polynomial extrapolation of degree four and lower. |

### Example of adding `resilience_options`

with the Estimator primitive

```
from qiskit_ibm_runtime import QiskitRuntimeService, Estimator, Options
service = QiskitRuntimeService()
options = Options()
options.optimization_level = 1
options.resilience_level = 2
options.resilience.noise_factors = (1, 2, 3, 4)
options.resilience.noise_amplifier = 'CxAmplifier'
options.resilience.extrapolator = 'QuadraticExtrapolator'
backend = service.least_busy(operational=True, simulator=False)
estimator = Estimator(options=options, backend=backend)
job = estimator.run(circuits=[psi1], observables=[H1], parameter_values=[theta1])
psi1_H1 = job.result()
```

## Next steps

- Walk through an example that uses error mitigation in the Cost function lesson(opens in a new tab) in IBM Quantum Learning.
- Learn more about Q-CTRL(opens in a new tab).
- Learn how to transpile locally in the Transpile section.
- Try the Submit pre-transpiled circuits(opens in a new tab) tutorial.