qiskit-documentation/docs/guides/configure-error-mitigation.mdx

508 lines
27 KiB
Plaintext

---
title: Configure error mitigation
description: How to configure error mitigation with Qiskit Runtime.
---
# 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.
<admonition type="note">Sampler V2 does not support specifying resilience levels. However, you can turn on or off individual error mitigation / suppression methods. See the [Custom error settings](#advanced-error) section for details.</admonition>
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.
<Admonition type="info" title="Attention">
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.
</Admonition>
<Admonition type="caution" title="Important">
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](./transpile) 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 V1 primitives optimize the input circuits. To bypass all optimization when using a V1 primitive, 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.
``` python
service = QiskitRuntimeService(channel="ibm_cloud", channel_strategy="q-ctrl")
```
</Admonition>
<span id="resilience-table"></span>
<Tabs>
<TabItem value="PrimV2" label="V2 primitives">
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
</TabItem>
<TabItem value="PrimV1" label="V1 primitives">
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) | - |
</TabItem>
</Tabs>
<Admonition type="info" title="Attention">
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.
</Admonition>
<Admonition type="note">
If using an IBM Cloud&reg; Qiskit Runtime service instance with Q-CTRL performance management enabled, do not 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](https://docs.q-ctrl.com/q-ctrl-embedded).
</Admonition>
## 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.](#advanced-error) You cannot specify resilience levels in Sampler V2. However, you can set custom techniques individually.
<details>
<summary>Resilience Level 0</summary>
No error mitigation is applied to the user program.
</details>
<details>
<summary>Resilience Level 1</summary>
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](https://arxiv.org/abs/2012.09738).
</details>
<details>
<summary>Resilience Level 2</summary>
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.
![This image shows a graph. The x-axis is labeled Noise amplification factor. The y-axis is labeled Expectation value. An upward sloping line is labeled Mitigated value. Points near the line are noise-amplified values. There is a horizontal line just above the X-axis labeled Exact value. ](/images/optimize/resilience-2.png "Illustration of the ZNE method")
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](https://arxiv.org/abs/2012.09738).
</details>
### 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`.
```python
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})
```
<Admonition type="info" title="Note">
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.
</Admonition>
## Configure Estimator (V1) with resilience levels
<details>
<summary>Resilience Level 0</summary>
No error mitigation is applied to the user program.
</details>
<details>
<summary>Resilience Level 1</summary>
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](https://arxiv.org/abs/2012.09738).
</details>
<details>
<summary>Resilience Level 2</summary>
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.
![This image shows a graph. The x-axis is labeled Noise amplification factor. The y-axis is labeled Expectation value. An upward sloping line is labeled Mitigated value. Points near the line are noise-amplified values. There is a horizontal line just above the X-axis labeled Exact value. ](/images/optimize/resilience-2.png "Illustration of the ZNE method")
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.
</details>
<details>
<summary>Resilience Level 3</summary>
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.
<figure>
<img src="/images/optimize/stratified.png" alt="Stratified circuit illustration. There are arbitrary single-qubit gates between each `layer`. Each layer is defined by a block that crosses multiple qubit wires." />
<figcaption>This is an example of a <span
class="title-ref">stratified</span> circuit, where the layers of
two-qubit gates are labeled layer 1 through n. Note that each <span
class="math inline"><em>U</em><sub><em>n</em></sub></span> is composed
of two-qubit gates on the native connectivity graph of the quantum
processor. The open boxes represent arbitrary single-qubit
gates.</figcaption>
</figure>
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.
![This image shows that the error decreases as the number of samples increases. The accuracy is best with a high sampling overhead (1000) and worst with a low sampling overhead (1.1).](/images/optimize/sampling-overhead.png)
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.
</details>
### 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`.
```python
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)
```
<Admonition type="info" title="Note">
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.
</Admonition>
## Configure Sampler (V1) with resilience levels
<admonition type="note">Sampler V2 does not support specifying resilience levels. However, you can turn on or off individual error mitigation / suppression methods. See [Custom error settings](#advanced-error) for details.</admonition>
The Sampler V1 default resilience setting (level 1) enables readout error
mitigation to allow users to generate mitigated quasi-probability
distributions.
<details>
<summary>Resilience Level 1</summary>
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.
![Illustration of the M3 method.](/images/optimize/m3.png "M3 method")
</details>
```python
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)
```
<span id="advanced-error"></span>
## 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.
<Admonition type = "note" title = "Notes">
- Not all options are available for both primitives. See the [API reference](/api/qiskit-ibm-runtime/options) for the list of available options.
- Dynamical decoupling is not supported when the input circuits are dynamic.
</Admonition>
<Tabs>
<TabItem value="EstimatorV2" label="Estimator V2">
```python
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}")
```
</TabItem>
<TabItem value="Sampler V2" label="Sampler V2">
```python
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}")
```
</TabItem>
</Tabs>
## 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\])` <br/> 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
```python
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, mode=backend)
job = estimator.run(circuits=[psi1], observables=[H1], parameter_values=[theta1])
psi1_H1 = job.result()
```
<span id="no-error-mitigation"></span>
## Turn off all error mitigation and error suppression
You can turn off all error mitigation and suppression if you are, for example, doing research on your own mitigation techniques. To accomplish this, for EstimatorV2, set `resilience_level = 0`. For SamplerV2, no changes are necessary because no error mitigation or suppression options are enabled by default.
Example:
Turn off all error mitigation and suppression in EstimatorV2.
```python
from qiskit_ibm_runtime import EstimatorV2 as Estimator, Options, QiskitRuntimeService
# Define the service. This allows you to access IBM Quantum systems.
service = QiskitRuntimeService()
# Get a backend
backend = service.least_busy(operational=True, simulator=False)
# Define Estimator
estimator = Estimator(backend)
options = estimator.options
# Turn off all error mitigation and suppression
options.resilience_level = 0
```
## Next steps
<Admonition type="tip" title="Recommendations">
- Walk through an example that uses error mitigation in the [Cost function lesson](https://learning.quantum.ibm.com/course/variational-algorithm-design/cost-functions#primitives) in IBM Quantum Learning.
- Learn more about [Q-CTRL](https://docs.q-ctrl.com/q-ctrl-embedded).
- Learn how to transpile locally in the [Transpile](./transpile/) section.
- Try the [Submit pre-transpiled circuits](https://learning.quantum.ibm.com/tutorial/submitting-user-transpiled-circuits-using-primitives) tutorial.
</Admonition>