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

Simulate a kicked Ising model with the TEM function

Algorithmiq's Tensor-network Error Mitigation (TEM) method is a hybrid quantum-classical algorithm that removes the effect of hardware noise entirely in classical post-processing. The circuit runs on the QPU as written, with an informationally complete (IC) measurement at the end. A tensor network that inverts the learned noise of the device is then applied to the measurement outcomes, giving error-mitigated expectation values.

This tutorial reproduces, at 31 qubits, the kind of many-body dynamics experiment run on up to 91 qubits in L. E. Fischer et al., Nat. Phys. (2026). It shows:

  • How much signal hardware noise destroys in a utility-scale dynamics circuit, and how much TEM recovers.
  • How TEM compares with probabilistic error cancellation (PEC) and zero-noise extrapolation (ZNE) on the same circuit.

The IC measurement also makes it possible to estimate observables that were not requested when the circuit ran, with a rerun of only the classical post-processing. For an example that estimates the full light cone of a chain, see Run 4: measure the light cone from the same data.

To tune TEM's accuracy against its QPU and classical cost, see the companion example Tune the TEM function for accuracy and cost.

Usage estimate: approximately 20 QPU seconds for TEM on ibm_phoenix (the QPU time depends heavily on the chosen device). The optional PEC and ZNE comparison takes about 35 QPU minutes more, almost all of it for PEC.


Background: the kicked Ising chain

The kicked Ising model alternates an Ising evolution on a chain of NN qubits,

H^I=J∑n=0N−2Z^nZ^n+1+h∑n=0N−1Z^n,\hat{H}_{\text{I}} = J \sum_{n=0}^{N-2} \hat{Z}_n \hat{Z}_{n+1} + h \sum_{n=0}^{N-1} \hat{Z}_n ,

with a transverse kick,

H^K=b∑n=0N−1X^n.\hat{H}_{K} = b \sum_{n=0}^{N-1} \hat{X}_n .

One period of the dynamics is the Floquet unitary U^KI=e−iH^Ke−iH^I\hat{U}_{\text{KI}} = e^{-i \hat{H}_K} e^{-i \hat{H}_I}. On a quantum computer each period is a brickwork of two-qubit ZZZZ rotations followed by single-qubit rotations, so the circuit contains only two distinct layers of two-qubit gates, repeated.

The quantity of interest is the infinite-temperature autocorrelation function of the first spin. The reference paper shows that it can be measured by preparing the first qubit in ∣+⟩|+\rangle and every other pair of qubits in the Bell state (∣00⟩+∣11⟩)/2(|00\rangle + |11\rangle)/\sqrt{2}, evolving for tt periods, and measuring a single-qubit Pauli operator X^n\hat{X}_n.

At the dual unitary point ∣J∣=∣b∣=π/4|J| = |b| = \pi/4 the model is exactly solvable:

  • The correlation travels along the chain at maximal speed, so after tt periods only qubit n=tn = t carries it and ⟨X^n≠t⟩=0\langle \hat{X}_{n \neq t} \rangle = 0.
  • On that qubit, ⟨X^n=t⟩=[cos⁡(2h)]t\langle \hat{X}_{n=t} \rangle = [\cos(2h)]^t.

These exact values make the model a sharp benchmark for error mitigation: the signal that reaches qubit tt has passed through every layer of the circuit, so it is exposed to all the noise of the device, yet its noiseless value is known. Away from the dual unitary point the same circuits become hard to simulate classically, which is where the paper uses TEM to go beyond exact methods.

TEM works in three steps: it learns the noise of each distinct layer of two-qubit gates and the readout error, runs the circuit with an IC measurement, and finally applies the noise-inverting tensor network to the measurement outcomes on IBM Cloud®.


Setup

As a prerequisite, ensure that the necessary dependencies are installed.

%pip install numpy matplotlib qiskit qiskit-ibm-catalog qiskit-ibm-runtime pylatexenc
import numpy as np

from qiskit.quantum_info import SparsePauliOp

from qiskit_ibm_catalog import FunctionsCatalog

Step 1: Build the circuit and the observables

This tutorial uses a circuit that implements the kicked Ising model described in the previous section. The circuit is prepared as follows. First, there is a state preparation phase, in which the first qubit is in the state ∣+⟩|+\rangle, while the others are in Bell pairs (∣00⟩+∣11⟩)/2(|00\rangle + |11\rangle)/\sqrt{2}. This is followed by the brickwork structure that implements the unitary evolution U^KI\hat{U}_{\text{KI}}. The number of physical time steps corresponds to t/2t/2 circuit layers.

The following code builds the circuit used in this tutorial.

from qiskit import QuantumCircuit


def kicked_ising_circuit(n_qubits, t_steps):
    """Kicked Ising circuit at the dual unitary point (J = b = pi/4, h = 0)."""
    circuit = QuantumCircuit(n_qubits)

    # State preparation: |+> on qubit 0, Bell pairs on (1, 2), (3, 4), ...
    circuit.h(0)
    for i in range(1, n_qubits - 1, 2):
        circuit.h(i)
        circuit.x(i + 1)
        circuit.cx(i, i + 1)
    circuit.barrier()

    # Clifford two-qubit block: one ZZ rotation, X kick, one ZZ rotation
    block = QuantumCircuit(2)
    block.sdg([0, 1])
    block.cx(0, 1)
    block.sdg(0)
    block.h([0, 1])
    block.s(1)
    block.cx(0, 1)
    block.s(0)
    block.h(0)
    block.sdg(0)
    block.y(1)
    block.h(1)

    # Brickwork: even periods act on (0, 1), (2, 3), ...; odd periods on (1, 2), (3, 4), ...
    for step in range(t_steps):
        for q in range(step % 2, n_qubits - 1, 2):
            circuit.compose(block, [q, q + 1], inplace=True)
        circuit.barrier()
    return circuit

Next, build the observable, X^n=t\hat{X}_{n=t}. It is constructed as a simple Pauli string with the order matching the one used by Qiskit:

def xt_observable(n_qubits, t_steps):
    pauli_str = "".join(["I" * t_steps, "X", "I" * (n_qubits - t_steps - 1)])
    pauli_str = pauli_str[::-1]  # Reverse the string to match qiskit order
    return SparsePauliOp(data=pauli_str, coeffs=1.0)

The experiment uses 31 qubits and 15 periods at h=0h = 0, so the exact value of ⟨X^n=15⟩\langle \hat{X}_{n=15} \rangle is 1. This is a utility-scale circuit with 465 two-qubit gates: 15 that prepare the Bell pairs and 30 in each period. The signal that reaches qubit 15 passes through hundreds of them.

# Kicked Ising model parameters
n_qubits = 31
t_steps = 15
h = 0.0

# Build the circuit for the kicked Ising model
circuit = kicked_ising_circuit(n_qubits=n_qubits, t_steps=t_steps)


# Build the observable for the kicked Ising model
observable = xt_observable(n_qubits=n_qubits, t_steps=t_steps)

Step 2: Run TEM on the QPU

Next, get access to the TEM function and select a backend from the available devices. This code assumes you've already saved your account to your local environment.

# Select the QPU backend
backend_name = "ibm_phoenix"  # Replace with your desired backend's name

Load the TEM function from the IBM Quantum® Functions Catalog:

# Load the TEM function from the Quantum Functions Catalog
catalog = FunctionsCatalog()
tem = catalog.load("algorithmiq/tem")

Transpile the circuit for the chosen device once, and map the observable onto the qubits it was placed on. TEM accepts this instruction set architecture (ISA) circuit as it is, and the PEC and ZNE comparison in Step 3 uses the same circuit, so all methods run the same gates on the same qubits.

from qiskit.transpiler import generate_preset_pass_manager
from qiskit_ibm_runtime import QiskitRuntimeService

service = QiskitRuntimeService()
backend = service.backend(backend_name)

pass_manager = generate_preset_pass_manager(
    optimization_level=3, backend=backend
)
isa_circuit = pass_manager.run(circuit)
isa_observable = observable.apply_layout(isa_circuit.layout)

# Collect the input PUBs, in this case composed of a single circuit and observable
pubs = [(isa_circuit, [isa_observable])]

The following options are based on the physics of the circuit:

  • max_layers_to_learn: 4: an upper bound on the number of distinct layers of two-qubit gates whose noise is learned. The brickwork has only two distinct layers, so only those two are learned.
  • default_shots: 100_000: the number of shots of the IC measurement, which sets the statistical precision of the estimate.
  • tem_max_bond_dimension: 128 and tem_compression_cutoff: 1e-14: a moderate bond dimension that keeps the classical post-processing fast at 31 qubits, with a small cutoff so that the bond dimension is not truncated further.
  • private: False: keeps the job results downloadable later. Set it to True for confidential circuits.

The performance tuning example explains each of these options in detail.

options = {
    "num_randomizations": 32,
    "max_layers_to_learn": 4,
    "shots_per_randomization": 128,
    "layer_pair_depths": [0, 1, 2, 4, 16, 32],
    "default_shots": 100_000,
    "tem_max_bond_dimension": 128,
    "tem_compression_cutoff": 1e-14,
    "private": False,
}

Calculate the function size that the job needs with the size calculator provided by IBM®, and pass it to tem.run as function_size. The calculator maps the circuit onto the backend and returns S, M, or L without submitting anything; see Function sizes.

# Calculate the function size a circuit needs, before submitting it.
#
# Call ``calculate_function_size(pubs, backend)``: it returns "S", "M" or "L" and submits
# nothing. Pass the whole list of PUBs -- a job runs at one size, and the heaviest PUB
# decides it. The circuit is measured after being mapped onto ``backend``, since mapping
# can add both qubits and depth.

from collections.abc import Iterable
from typing import Any, Literal

from qiskit.circuit import Barrier
from qiskit.circuit.equivalence_library import SessionEquivalenceLibrary
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import (
    ApplyLayout,
    BarrierBeforeFinalMeasurements,
    BasisTranslator,
    EnlargeWithAncilla,
    FilterOpNodes,
    FullAncillaAllocation,
    HighLevelSynthesis,
    SabreSwap,
    TrivialLayout,
    UnitarySynthesis,
)

Size = Literal["S", "M", "L"]
_ORDER = {"S": 0, "M": 1, "L": 2}

# Limits are provided by IBM
_SMALL_QUBITS, _SMALL_DEPTH_2Q = 40, 40
_MEDIUM_QUBITS, _MEDIUM_DEPTH_2Q = 100, 100

# Any fixed value works; what matters is that it does not change between calls.
_SEED_TRANSPILER = 42

# Added by BarrierBeforeFinalMeasurements so routing cannot move gates past a measurement,
# then removed again once routing is done.
_PROTECTION_BARRIER = "qiskit.transpiler.internal.routing.protection.barrier"


def calculate_function_size(
    circuit: QuantumCircuit | Iterable[Any], backend, **kwargs: Any
) -> Size:
    """Return the size ("S", "M" or "L") required to run the function."""
    circuits = pub_circuits(circuit)
    if not circuits:
        raise ValueError(
            "No circuit to size: pass a QuantumCircuit or a non-empty list of PUBs."
        )
    return max(
        (_calculate_circuit_size(qc, backend, **kwargs) for qc in circuits),
        key=_ORDER.__getitem__,
    )


def _calculate_circuit_size(
    circuit: QuantumCircuit, backend, **kwargs: Any
) -> Size:
    """Return the size required to run a single circuit."""
    metrics = _measure(circuit, backend, **kwargs)
    if _is_small(metrics):
        return "S"
    if _is_medium(metrics):
        return "M"
    return "L"


def pub_circuits(problem: Any) -> list[QuantumCircuit]:
    """Return the circuits in ``problem``: one circuit, or one per PUB in a list."""
    if isinstance(problem, QuantumCircuit):
        return [problem]
    circuits: list[QuantumCircuit] = []
    for index, pub in enumerate(problem):
        if isinstance(pub, QuantumCircuit):
            circuit = pub
        elif isinstance(getattr(pub, "circuit", None), QuantumCircuit):
            circuit = pub.circuit
        elif (
            isinstance(pub, (tuple, list))
            and pub
            and isinstance(pub[0], QuantumCircuit)
        ):
            circuit = pub[0]
        else:
            raise ValueError(f"PUB #{index} has no QuantumCircuit to size.")
        circuits.append(circuit)
    return circuits


def _pass_manager(target) -> PassManager:
    """Return the pass manager used to map a circuit onto ``target``.

    Fixed and seeded, so the same circuit always gives the same size.
    """
    basis = list(target.operation_names)
    library = SessionEquivalenceLibrary
    return PassManager(
        [
            UnitarySynthesis(
                basis, approximation_degree=1.0, min_qubits=3, target=target
            ),
            HighLevelSynthesis(
                target=target,
                equivalence_library=library,
                basis_gates=basis,
                min_qubits=3,
            ),
            BasisTranslator(library, basis, target=target, min_qubits=3),
            TrivialLayout(target),
            FullAncillaAllocation(target),
            EnlargeWithAncilla(),
            ApplyLayout(),
            BarrierBeforeFinalMeasurements(label=_PROTECTION_BARRIER),
            SabreSwap(
                target, heuristic="basic", seed=_SEED_TRANSPILER, trials=5
            ),
            FilterOpNodes(lambda node: node.label != _PROTECTION_BARRIER),
            UnitarySynthesis(basis, approximation_degree=1.0, target=target),
            HighLevelSynthesis(
                target=target,
                equivalence_library=library,
                basis_gates=basis,
                use_qubit_indices=True,
            ),
            BasisTranslator(library, basis, target=target),
        ]
    )


def _count(isa: QuantumCircuit) -> dict:
    """Return the active qubits and two-qubit-gate depth of a mapped circuit."""
    active = {
        q
        for instr in isa.data
        if not isinstance(instr.operation, Barrier)
        for q in instr.qubits
    }
    return {
        "num_qubits": len(active),
        "depth_2q": isa.depth(
            filter_function=lambda instr: len(instr.qubits) == 2
            and not isinstance(instr.operation, Barrier)
        ),
    }


def _measure(circuit: QuantumCircuit, backend, **kwargs: Any) -> dict:
    """Map ``circuit`` onto ``backend`` and return its metrics."""
    return _count(_pass_manager(backend.target).run(circuit))


def _is_small(metrics: dict) -> bool:
    """Determine if the metrics fit T-size 'S'."""
    return (
        metrics["num_qubits"] <= _SMALL_QUBITS
        and metrics["depth_2q"] <= _SMALL_DEPTH_2Q
    )


def _is_medium(metrics: dict) -> bool:
    """Determine if the metrics fit T-size 'M'."""
    return (
        metrics["num_qubits"] <= _MEDIUM_QUBITS
        and metrics["depth_2q"] <= _MEDIUM_DEPTH_2Q
    )
size = calculate_function_size(pubs, backend)  # "S", "M" or "L"
print(size)

Output:

S

Finally, run the experiment, get the result, and visualize it. This step takes approximately 20 QPU seconds on ibm_phoenix.

tem_job_large = tem.run(
    pubs=pubs, backend_name=backend_name, options=options, function_size=size
)

Save the job ID. Use it to retrieve the results later with catalog.get_job_by_id(job_id), or to rerun the post-processing.

job_id = tem_job_large.job_id  # save this job_id for later use
print(f"Job ID: {job_id}")

Output:

Job ID: cbe78e03-63ec-43d8-8f59-cee8a3eae983
print(tem_job_large.status())

Output:

DONE
results_large = tem_job_large.result()
tem_evs = results_large[0].data.evs[0]
tem_std = results_large[0].data.stds[0]

print(f"TEM Result: {tem_evs:.3f} ± {tem_std:.3f}")


# Get the metadata of the TEM job
job_metadata = tem_job_large.result().metadata

# Get the runtime of the TEM job
qpu_runtime = job_metadata["resource_usage"]["RUNNING: EXECUTING_QPU"][
    "QPU_TIME"
]
classical_runtime = (
    job_metadata["resource_usage"]["RUNNING: OPTIMIZING_FOR_HARDWARE"][
        "CPU_TIME"
    ]
    + job_metadata["resource_usage"]["RUNNING: POST_PROCESSING"]["CPU_TIME"]
)

print(f"QPU Runtime: {qpu_runtime} seconds")
print(f"Classical Runtime: {classical_runtime} seconds")

Output:

TEM Result: 1.063 ± 0.007
QPU Runtime: 19.0 seconds
Classical Runtime: 1662.53475 seconds

Step 3: Compare with PEC and ZNE

The result metadata also contains the unmitigated estimate, computed from the same measurement outcomes without the noise-inverting network. A comparison of the two with the exact value shows how much of the signal the noise destroys, and how much TEM recovers:

To put the TEM result in context, run the same circuit with two other error mitigation methods: probabilistic error cancellation (PEC) and zero-noise extrapolation (ZNE) with probabilistic error amplification (PEA).

Caution

The following code runs a large PEC experiment, which requires around 40 minutes of QPU time.

from qiskit_ibm_runtime import EstimatorV2 as Estimator
from qiskit_ibm_runtime.noise_learner import NoiseLearner

# Learn the noise of the layers of two-qubit gates, with the same settings as TEM
noise_learner = NoiseLearner(
    mode=backend,
    options={
        "max_layers_to_learn": 4,
        "num_randomizations": 32,
        "shots_per_randomization": 128,
        "layer_pair_depths": [0, 1, 2, 4, 16, 32],
    },
)
noise_learner_job = noise_learner.run([isa_circuit])
layer_noise_model = noise_learner_job.result()

pec_estimator = Estimator(
    mode=backend,
    options={
        "default_shots": 100_000,
        "resilience": {
            "measure_mitigation": True,
            "pec_mitigation": True,
            "pec": {"max_overhead": 1000, "noise_gain": "auto"},
            "layer_noise_model": layer_noise_model,
        },
        "twirling": {"enable_gates": True, "enable_measure": True},
    },
)
zne_estimator = Estimator(
    mode=backend,
    options={
        "resilience": {
            "measure_mitigation": True,
            "zne_mitigation": True,
            "zne": {
                "amplifier": "pea",
                "noise_factors": [1.0, 1.5, 2.0, 2.5, 3.0],
                "extrapolator": ["exponential", "linear"],
            },
            "layer_noise_model": layer_noise_model,
        },
        "twirling": {
            "enable_gates": True,
            "enable_measure": True,
            "num_randomizations": 100,
            "shots_per_randomization": 200,
        },
    },
)
pec_job = pec_estimator.run([(isa_circuit, isa_observable)])
zne_job = zne_estimator.run([(isa_circuit, isa_observable)])

pec_evs, pec_std = pec_job.result()[0].data.evs, pec_job.result()[0].data.stds
zne_evs, zne_std = zne_job.result()[0].data.evs, zne_job.result()[0].data.stds


print(f"PEC Result: {pec_evs[0]:.3f} ± {pec_std[0]:.3f}")
print(f"ZNE Result: {zne_evs[0]:.3f} ± {zne_std[0]:.3f}")
# Table comparing the different expectation values
metadata_large = results_large[0].metadata
unmitigated_evs = metadata_large["evs_wo_tem_wo_qdt"][0]
unmitigated_stds = metadata_large["stds_wo_tem_wo_qdt"][0]

exact_evs = np.cos(2 * h) ** t_steps

print(f"{'Method':<12}{'Value':>8}{'Std':>8}")
for method, value, std in [
    ("Unmitigated", unmitigated_evs, unmitigated_stds),
    ("ZNE", zne_evs[0], zne_std[0]),
    ("PEC", pec_evs[0], pec_std[0]),
    ("TEM", tem_evs, tem_std),
]:
    print(f"{method:<12}{value:>8.3f}{std:>8.3f}")
print(f"{'Exact':<12}{exact_evs:>8.3f}")

Output:

Method         Value     Std
Unmitigated    0.879   0.005
ZNE            0.924   0.023
PEC            0.940   0.149
TEM            1.063   0.007
Exact          1.000

Note: Each mitigation method can produce expectation values that are either higher or lower than the exact result. The standard deviations reflect statistical uncertainty only; they do not account for inaccuracies in the characterized noise model, because that model has no associated error bound.

# QPU time of each method on `ibm_phoenix`, in seconds.

# Read the QPU time of the jobs run above. The noise learning is shared by PEC and
# ZNE, so its QPU time is added to both.
noise_learning_time = noise_learner_job.usage()
qpu_times = {
    "ZNE": zne_job.usage() + noise_learning_time,
    "PEC": pec_job.usage() + noise_learning_time,
    # TEM reports its QPU time in the metadata of the job result (see Step 2)
    "TEM": tem_job_large.result().metadata["resource_usage"][
        "RUNNING: EXECUTING_QPU"
    ]["QPU_TIME"],
}

for method, qpu_time in qpu_times.items():
    print(f"{method}: QPU {qpu_time:.0f} s")

Output:

ZNE: QPU 18 s
PEC: QPU 2074 s
TEM: QPU 19 s

The unmitigated value decays with the number of noisy gates in the light cone of qubit 15, so at this depth most of the signal is lost. TEM removes this decay in post-processing, recovering most of the signal without running any additional circuits. The remaining gap to the exact value comes from the speed-oriented settings used in this tutorial: a bond dimension of 128 and a modest noise-learning budget. The performance tuning example shows how to trade QPU and classical time for accuracy.


Next steps