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.

Get started with Algorithmiq TEM

See the overview and the API reference

Note

IBM Quantum® Functions are a beta feature available only to IBM Quantum Premium Plan, Flex Plan, and On-Prem (through the IBM Quantum Platform API) Plan users. Beta features are subject to change.

  • The code on this page was developed using the following requirements. We recommend using these versions or newer.

    qiskit[all]~=2.3.0
    qiskit-ibm-catalog~=0.11.0
    

Set up and load the function

Authenticate using your IBM Quantum Platform API key, and select the TEM function as follows. (This snippet assumes you've already saved your account to your local environment.)

from qiskit_ibm_catalog import FunctionsCatalog

tem_function_name = "algorithmiq/tem"
catalog = FunctionsCatalog(channel="ibm_quantum_platform")

# Load your function
tem = catalog.load(tem_function_name)

Function sizes

Every job runs at one size: S, M, or L. If the size is too small, the job is rejected. If it is larger than needed, the job runs on a bigger compute profile than the work requires. See Function sizes for how sizes work in general.

The size comes from your circuit after it is mapped onto the backend that you target: the number of qubits that carry an operation, and the two-qubit-gate depth. Mapping can add both, so a circuit is sized as it runs, not as you wrote it.

Size
Smallest size for active qubits and two-qubit-gate depth
Compute profile
vCPU
RAM
GPUs
Sboth at most 40General Medium (16x128)16128 GB—
Mboth at most 100General Medium (16x128)16128 GB—
Leither above 100Accelerated Large (80x1200x8a100)801200 GB8 × A100

A circuit must fit both bounds of a size, so 30 qubits at a two-qubit-gate depth of 120 is L, not S. These are the same bounds for every circuit function, so a size means the same difficulty of circuit whichever one you call.

The default is M, used when a job does not request a size.

You can also get the mapping from the function with tem.sizes_map, and the size that is used when a job does not request one with tem.default_size.

Choose a size for TEM

The circuit sets the smallest size that a job can run at. The memory that TEM's classical post-processing needs depends mostly on the bond dimension of the tensor network (tem_max_bond_dimension), not on the circuit size, so a small circuit can still need more memory than its size provides. S and M run on the same compute profile; request L when the post-processing needs more memory than General Medium has, for example at a large bond dimension. The dry_run option estimates the peak memory and returns the size it needs as classical_compute_size_tag; see Tune the TEM function for accuracy and cost. A job that requests a larger size than its circuit needs records a 4601 advisory event. When you request L for the memory of the post-processing, this event is expected, and the job runs normally.

A rerun (the job_id option) and a dry run submit no new QPU jobs, so their size is not checked against the circuit: they run at the size that you request, or at the default. Choose the size of a rerun from the memory its post-processing needs.

Calculate the size before submitting

Run the following code on your own circuits. It only reads the circuits. It submits no job and reserves nothing, so you can call it as often as needed while you reduce a circuit to a smaller size.

It needs the backend as well as the circuits, because the size depends on the coupling map they are mapped onto. It requires only Qiskit.

Size the circuit that you submit after you transpile it

TEM transpiles a non-ISA circuit with optimal settings before running it, but the size calculator maps it with a fixed, simpler layout and routing, which can add many qubits and much depth: a circuit can size as L before transpilation and as S after. The function checks the size on the circuits that you pass, so transpile them for the backend first, and pass the same ISA circuits to the calculator and to tem.run.

# 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 import QuantumCircuit
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
    )

Pass the whole list of PUBs, not one at a time. A job runs at a single size, so the heaviest PUB decides it: one deep circuit among many shallow ones makes the whole job L. Splitting the batch into separate jobs lets the lighter circuits run at a smaller size.

If the size is too small, the job fails with error 4600 and the message names the size to use instead. If it is larger than needed the job runs normally and records a 4601 advisory event. See the managed workflow documentation to learn more.

The following example calculates the size of its circuit and passes it to tem.run as function_size.


Example

The following example uses TEM to compute the expectation value of an observable for a simple quantum circuit.

from qiskit.quantum_info import SparsePauliOp

# Prepare a 4-qubit GHZ state, (|0000> + |1111>) / sqrt(2)
num_qubits = 4
ghz = QuantumCircuit(num_qubits)
ghz.h(0)
for qubit in range(num_qubits - 1):
    ghz.cx(qubit, qubit + 1)

# Z on qubits 0 and 3: a stabilizer of the GHZ state, with exact value 1
observable = SparsePauliOp("ZIIZ", 1.0)

# Define the execution options
ghz_pub = (ghz, [observable])
options = {"default_precision": 0.01}
# Define backend to use
backend_name = "ibm_kingston"

Calculate the size the job needs on the target backend, and pass it to tem.run:

backend = catalog.backend(backend_name)
size = calculate_function_size([ghz_pub], backend)  # "S", "M" or "L"
print(size)

Output:

S
# Run the TEM function
ghz_job = tem.run(
    pubs=[ghz_pub],
    backend_name=backend_name,
    options=options,
    function_size=size,
)

Use the Qiskit Serverless APIs to check your quantum function workload's status:

print(ghz_job.status())

Return the results as follows:

idx = 0  # observable index, 0 in this case

ghz_result = ghz_job.result()[0]
ghz_ev = ghz_result.data.evs[idx]
ghz_std = ghz_result.data.stds[idx]
# Unmitigated value, from the same measurement outcomes
raw_ev = ghz_result.metadata["evs_wo_tem_wo_qdt"][idx]
print(
    f"ZIIZ: TEM {ghz_ev:+.3f} ± {ghz_std:.3f}, unmitigated {raw_ev:+.3f}, statevector {1.0}"
)

Output:

ZIIZ: TEM +0.952 ± 0.032, unmitigated +0.869, statevector 1.0

Next steps

Recommendations