Skip to content

Backends

Ten simulators behind one protocol. A backend supplies a statevector — or, for a device, counts — and sampling, basis rotation, qubit-wise-commuting grouping, expectation and the whole batch stack are derived once in base.py. That is what makes agreement between them a property rather than a coincidence, and it is why adding one is a single register_backend call.

The reference below was split out of Core because seven of the nine implementation modules that existed then had no entry anywhere: their constructor options, their refusals and their approximations were readable only in the source. A backend that silently truncates past a bond dimension, or refuses a GPU it cannot find, should say so on the page you look it up on.

Which one supports what

supports_statevector and supports_exact are a contract, not metadata — they decide which gradients, diagnostics and metrics are even legal on a given backend. Anything needing a statevector (adjoint differentiation, the metric tensor, expressibility, diagnose's structural checks) refuses rather than substituting a sampled stand-in.

Backend statevector exact notes
numpy yes yes the reference. Vectorised, with gate fusion; hard cap at 24 qubits
aer yes yes C++ statevector, faster above ~13 qubits
mps no until truncation matrix-product state; wide but lightly entangled circuits
qiskit yes yes quantum_info.Statevector, the slowest of the exact three
cirq yes yes Cirq's reference simulator
openqarp yes yes C++ core; contracts expectations itself and sweeps a batch of them without returning to Python
spinqit yes yes Python 3.10 only
torch yes yes differentiable — the only one backprop can use
cirq-density no yes, given the noise model density matrix
qiskit-aer no yes, given the noise model density matrix

"Exact given the noise model" is deliberate on the two mixed-state rows: they return a shot-free number, exact for the channel you asked for. That is not the same as the noiseless answer, and diagnose separates the two rather than reporting their product.

The protocol

base

The backend protocol.

A backend supplies primitives; this base class supplies semantics. A simulator backend needs to implement only :meth:statevector — sampling, basis rotation and expectation values are derived here, so every backend agrees on what a shot is and what an expectation means. A sampling-only device overrides :meth:counts instead.

That split is what makes cross-backend equivalence testable rather than hopeful: if two backends disagree, the disagreement is in the circuit translation, not in four separate re-implementations of the measurement logic.

BackendNotAvailable

Bases: RuntimeError

Raised when a backend's underlying SDK is not installed or not importable.

Backend

Backend(seed: int | None = None)

A device or simulator that can run a :class:CircuitSpec.

Source code in src/qmlkit/core/backends/base.py
def __init__(self, seed: int | None = None) -> None:
    self._rng = np.random.default_rng(seed)
statevector
statevector(spec: CircuitSpec) -> NDArray[Any]

Final state as a flat 2**n complex vector, qubit 0 most significant.

Source code in src/qmlkit/core/backends/base.py
def statevector(self, spec: CircuitSpec) -> npt.NDArray[Any]:
    """Final state as a flat ``2**n`` complex vector, qubit 0 most significant."""
    raise NotImplementedError(
        f"the {self.name!r} backend cannot produce a statevector; use shots=N to sample instead"
    )
counts
counts(
    spec: CircuitSpec, shots: int, seed: int | None = None
) -> dict[str, int]

Sample the computational basis. Keys are n_qubits-wide bitstrings.

The default samples the exact probability distribution — correct for any statevector simulator. A shot-based device overrides this.

Source code in src/qmlkit/core/backends/base.py
def counts(self, spec: CircuitSpec, shots: int, seed: int | None = None) -> dict[str, int]:
    """Sample the computational basis. Keys are ``n_qubits``-wide bitstrings.

    The default samples the exact probability distribution — correct for any
    statevector simulator. A shot-based device overrides this.
    """
    self._check_bound(spec)
    if shots <= 0:
        raise ValueError("shots must be positive")
    rng = np.random.default_rng(seed) if seed is not None else self._rng
    return sample_counts_from_probs(self.probabilities(spec), shots, spec.n_qubits, rng)
probabilities
probabilities(spec: CircuitSpec) -> NDArray[Any]

Exact outcome probabilities over the 2**n basis states.

Source code in src/qmlkit/core/backends/base.py
def probabilities(self, spec: CircuitSpec) -> npt.NDArray[Any]:
    """Exact outcome probabilities over the ``2**n`` basis states."""
    return np.abs(self.statevector(spec)) ** 2
statevector_batch_slots
statevector_batch_slots(
    spec: CircuitSpec, slot_angles: NDArray[Any]
) -> NDArray[Any]

States for one circuit at many slot-angle vectors: (batch, 2**n).

Slot space rather than logical-parameter space is the primitive because that is what differentiation needs: a shift rule moves one occurrence of a parameter, and a weight-tied parameter has several. Anything expressed in logical parameters cannot say that.

The default binds and simulates one row at a time, so every backend has a working implementation the moment it can produce a statevector. A backend that can do better overrides this one method and everything above it — batched expectations, batched gradients, the torch layer — speeds up with it.

This loop is also the one place a backend without a native batch spends a long workload, so it is where progress is reported from. A Gram matrix on Qiskit is a single call from the caller's side and thousands of simulations from here; anything reporting at the call would sit silent for minutes.

Source code in src/qmlkit/core/backends/base.py
def statevector_batch_slots(
    self, spec: CircuitSpec, slot_angles: npt.NDArray[Any]
) -> npt.NDArray[Any]:
    """States for one circuit at many **slot-angle** vectors: ``(batch, 2**n)``.

    Slot space rather than logical-parameter space is the primitive because that is
    what differentiation needs: a shift rule moves one *occurrence* of a parameter,
    and a weight-tied parameter has several. Anything expressed in logical
    parameters cannot say that.

    The default binds and simulates one row at a time, so every backend has a
    working implementation the moment it can produce a statevector. A backend that
    can do better overrides this one method and everything above it — batched
    expectations, batched gradients, the torch layer — speeds up with it.

    This loop is also the one place a backend *without* a native batch spends a
    long workload, so it is where progress is reported from. A Gram matrix on
    Qiskit is a single call from the caller's side and thousands of simulations
    from here; anything reporting at the call would sit silent for minutes.
    """
    from qmlkit.progress import task as progress_task

    rows = np.atleast_2d(np.asarray(slot_angles, dtype=float))
    states: npt.NDArray[Any] = np.empty((len(rows), 2**spec.n_qubits), dtype=complex)
    with progress_task(f"{self.name} circuits", len(rows)) as tracked:
        for i, row in enumerate(rows):
            states[i] = self.statevector(spec.with_slot_angles(row))
            tracked.advance()
    return states
statevector_batch
statevector_batch(
    spec: CircuitSpec, thetas: NDArray[Any]
) -> NDArray[Any]

States for one circuit at many logical parameter vectors.

Source code in src/qmlkit/core/backends/base.py
def statevector_batch(self, spec: CircuitSpec, thetas: npt.NDArray[Any]) -> npt.NDArray[Any]:
    """States for one circuit at many logical parameter vectors."""
    values = np.atleast_2d(np.asarray(thetas, dtype=float))
    return self.statevector_batch_slots(spec, spec.bind_slots_batch(values))
expectation_over_slots
expectation_over_slots(
    spec: CircuitSpec,
    slot_angles: NDArray[Any],
    obs: Observable,
    shots: int | None = None,
    seed: int | None = None,
) -> NDArray[Any]

<O> at many slot-angle vectors, in chunks of :attr:max_batch_rows.

This is the one call a batched gradient makes, and the one a device would turn into a job submission.

Source code in src/qmlkit/core/backends/base.py
def expectation_over_slots(
    self,
    spec: CircuitSpec,
    slot_angles: npt.NDArray[Any],
    obs: Observable,
    shots: int | None = None,
    seed: int | None = None,
) -> npt.NDArray[Any]:
    """``<O>`` at many slot-angle vectors, in chunks of :attr:`max_batch_rows`.

    This is the one call a batched gradient makes, and the one a device would turn
    into a job submission.
    """
    rows = np.atleast_2d(np.asarray(slot_angles, dtype=float))
    if shots is not None:
        return np.array(
            [self.expectation(spec.with_slot_angles(row), obs, shots, seed) for row in rows],
            dtype=float,
        )
    if not self.supports_exact:
        raise ValueError(f"the {self.name!r} backend has no exact mode; pass shots=N to sample")
    if not self.supports_statevector:
        # exact, but with no state to stack: fall back to one exact evaluation per
        # row. Slower, and still the path a batched parameter-shift gradient needs.
        return np.array(
            [self.expectation(spec.with_slot_angles(row), obs) for row in rows],
            dtype=float,
        )
    out = np.empty(rows.shape[0], dtype=float)
    for start in range(0, rows.shape[0], self.max_batch_rows):
        block = rows[start : start + self.max_batch_rows]
        states = self.statevector_batch_slots(spec, block)
        out[start : start + block.shape[0]] = expectation_from_statevectors(
            obs, states, spec.n_qubits
        )
    return out
expectation_over
expectation_over(
    spec: CircuitSpec,
    thetas: NDArray[Any],
    obs: Observable,
    shots: int | None = None,
    seed: int | None = None,
) -> NDArray[Any]

<O> for one circuit at many logical parameter vectors.

Source code in src/qmlkit/core/backends/base.py
def expectation_over(
    self,
    spec: CircuitSpec,
    thetas: npt.NDArray[Any],
    obs: Observable,
    shots: int | None = None,
    seed: int | None = None,
) -> npt.NDArray[Any]:
    """``<O>`` for one circuit at many logical parameter vectors."""
    values = np.atleast_2d(np.asarray(thetas, dtype=float))
    return self.expectation_over_slots(spec, spec.bind_slots_batch(values), obs, shots, seed)
expectation
expectation(
    spec: CircuitSpec,
    obs: Observable,
    shots: int | None = None,
    seed: int | None = None,
) -> float

<O>. shots=None means exact, where the backend supports it.

When sampling, terms are partitioned into qubit-wise-commuting groups and each group costs one circuit rather than one per term. On a simulator that is a modest saving; on a device, where circuit count is the binding constraint, it is the difference between Z0 + Z1 + Z2 + Z0Z2 costing four circuits and costing one.

Source code in src/qmlkit/core/backends/base.py
def expectation(
    self,
    spec: CircuitSpec,
    obs: Observable,
    shots: int | None = None,
    seed: int | None = None,
) -> float:
    """``<O>``. ``shots=None`` means exact, where the backend supports it.

    When sampling, terms are partitioned into qubit-wise-commuting groups and each
    group costs **one** circuit rather than one per term. On a simulator that is a
    modest saving; on a device, where circuit count is the binding constraint, it
    is the difference between ``Z0 + Z1 + Z2 + Z0Z2`` costing four circuits and
    costing one.
    """
    self._check_bound(spec)
    if shots is None:
        if not self.supports_exact:
            raise ValueError(
                f"the {self.name!r} backend has no exact mode; pass shots=N to sample"
            )
        if self.supports_statevector:
            return expectation_from_statevector(obs, self.statevector(spec), spec.n_qubits)
        # Exact probabilities without a statevector - a density-matrix simulator,
        # say. The basis rotation and the grouping are the ones the sampled path
        # uses; only the estimator differs, so "exact" and "sampled" cannot drift
        # apart in their measurement semantics.
        return sum(self._exact_group(spec, group) for group in group_qubit_wise_commuting(obs))
    return sum(
        self._sampled_group(spec, group, shots, seed)
        for group in group_qubit_wise_commuting(obs)
    )
expectation_variance
expectation_variance(
    spec: CircuitSpec, obs: Observable
) -> float

Variance of a single shot of the estimator for obs.

The estimator measures one circuit per qubit-wise-commuting group. Inside a group every term is diagonal in the measured basis, so the group contributes a diagonal operator whose variance comes straight from the outcome probabilities; groups use independent shots, so the variances add. Divide by the shot count for the squared standard error.

Exact, not a bound, and it reduces to c**2 - z**2 on a single term. Needs exact probabilities, so a sampling-only device cannot answer.

Source code in src/qmlkit/core/backends/base.py
def expectation_variance(self, spec: CircuitSpec, obs: Observable) -> float:
    """Variance of a *single shot* of the estimator for ``obs``.

    The estimator measures one circuit per qubit-wise-commuting group. Inside a
    group every term is diagonal in the measured basis, so the group contributes
    a diagonal operator whose variance comes straight from the outcome
    probabilities; groups use independent shots, so the variances add. Divide by
    the shot count for the squared standard error.

    Exact, not a bound, and it reduces to ``c**2 - z**2`` on a single term. Needs
    exact probabilities, so a sampling-only device cannot answer.
    """
    if not self.supports_exact:
        raise ValueError(
            f"the {self.name!r} backend cannot give an exact variance; it has no "
            "shot-free probabilities to compute one from"
        )
    self._check_bound(spec)
    total = 0.0
    for group in group_qubit_wise_commuting(obs):
        _, measured, rotated = self._group_circuit(spec, group)
        if rotated is None:
            continue  # identity terms are deterministic and contribute nothing
        probabilities = np.asarray(self.probabilities(rotated), dtype=float)
        diagonal = np.zeros_like(probabilities)
        for term in measured:
            zs = PauliString(tuple((q, "Z") for q, p in term.paulis if p != "I"), 1.0)
            diagonal += float(term.coeff.real) * diagonal_eigenvalues(zs, spec.n_qubits)
        mean = float(probabilities @ diagonal)
        total += float(probabilities @ diagonal**2) - mean**2
    return max(total, 0.0)

The registry

registry

Backend lookup, availability detection, and the process-wide default.

Every SDK is optional. Backends are constructed lazily and their imports deferred, so import qmlkit never requires Qiskit, Cirq or SpinQit to be installed - and asking for one that is missing produces an explanation and an install command rather than an ImportError traceback.

QMLKIT_BACKEND in the environment sets the default, which is the least intrusive way to run an existing script against a different SDK.

register_backend

register_backend(
    name: str,
    factory: Callable[..., Backend],
    requires: str | None = None,
    extra: str | None = None,
) -> None

Register a backend factory.

requires is the importable module the backend needs; extra is the pip extra that installs it. Both are used to report availability without importing.

Source code in src/qmlkit/core/backends/registry.py
def register_backend(
    name: str,
    factory: Callable[..., Backend],
    requires: str | None = None,
    extra: str | None = None,
) -> None:
    """Register a backend factory.

    ``requires`` is the importable module the backend needs; ``extra`` is the pip
    extra that installs it. Both are used to report availability without importing.
    """
    _REGISTRY[name] = (factory, requires, extra)

is_available

is_available(name: str) -> bool

True if this backend's SDK can be imported in the current interpreter.

Source code in src/qmlkit/core/backends/registry.py
def is_available(name: str) -> bool:
    """True if this backend's SDK can be imported in the current interpreter."""
    if name not in _REGISTRY:
        return False
    _, requires, _ = _REGISTRY[name]
    if requires is None:
        return True
    try:
        return importlib.util.find_spec(requires) is not None
    except (ImportError, ValueError):  # pragma: no cover - broken installs
        return False

list_backends

list_backends() -> tuple[str, ...]

Every registered backend name, installed or not.

Source code in src/qmlkit/core/backends/registry.py
def list_backends() -> tuple[str, ...]:
    """Every registered backend name, installed or not."""
    return tuple(sorted(_REGISTRY))

available_backends

available_backends() -> tuple[str, ...]

Only the backends whose SDK is actually importable right now.

Source code in src/qmlkit/core/backends/registry.py
def available_backends() -> tuple[str, ...]:
    """Only the backends whose SDK is actually importable right now."""
    return tuple(name for name in list_backends() if is_available(name))

backend_report

backend_report() -> str

A human-readable summary of which backends this interpreter can run.

Source code in src/qmlkit/core/backends/registry.py
def backend_report() -> str:
    """A human-readable summary of which backends this interpreter can run."""
    lines = ["qmlkit backends:"]
    for name in list_backends():
        _, requires, extra = _REGISTRY[name]
        if is_available(name):
            lines.append(f"  [ok]      {name}")
        else:
            hint = f"pip install 'qmlkit[{extra}]'" if extra else f"pip install {requires}"
            lines.append(f"  [missing] {name:8s} -> {hint}")
    return "\n".join(lines)

get_backend

get_backend(
    backend: str | Backend | None = None, **kwargs: object
) -> Backend

Resolve a backend name, instance, or None (the default) to an instance.

Source code in src/qmlkit/core/backends/registry.py
def get_backend(backend: str | Backend | None = None, **kwargs: object) -> Backend:
    """Resolve a backend name, instance, or ``None`` (the default) to an instance."""
    if isinstance(backend, Backend):
        return backend
    if backend is None:
        if "noise" in kwargs:
            raise _noise_needs_a_named_backend(None)
        return default_backend()
    try:
        factory, requires, extra = _REGISTRY[backend]
    except KeyError:
        raise unknown(
            "backend",
            backend,
            list_backends(),
            hint=f"Importable in this interpreter right now: {', '.join(available_backends())}.",
            error=KeyError,
        ) from None
    if requires is not None and not is_available(backend):
        hint = f"pip install 'qmlkit[{extra}]'" if extra else f"pip install {requires}"
        raise BackendNotAvailable(
            f"the {backend!r} backend needs {requires!r}, which is not installed here.\n"
            f"    {hint}\n"
            f"Available now: {', '.join(available_backends())}"
        )
    try:
        return factory(**kwargs)
    except TypeError as exc:
        if "noise" in kwargs and backend not in NOISY_BACKENDS:
            raise _noise_needs_a_named_backend(backend) from exc
        raise

require_statevector

require_statevector(
    backend: str | Backend | None, measure: str
) -> Backend

Resolve a backend for a quantity that only exists on a pure state.

Expressibility, Meyer-Wallach entanglement and the Fubini-Study metric are defined between state vectors. Handed a density-matrix backend they used to raise NotImplementedError from inside statevector(), several frames below anything the caller wrote. Naming the measure and the backend turns that into an answer.

This refuses rather than substituting the reference. Where the question is about the ansatz rather than the device - :func:~qmlkit.diagnostics.diagnose - the substitution is the right move and the report says so. Here the caller named a backend and asked for a measure on it.

Source code in src/qmlkit/core/backends/registry.py
def require_statevector(backend: str | Backend | None, measure: str) -> Backend:
    """Resolve a backend for a quantity that only exists on a pure state.

    Expressibility, Meyer-Wallach entanglement and the Fubini-Study metric are defined
    between *state vectors*. Handed a density-matrix backend they used to raise
    ``NotImplementedError`` from inside ``statevector()``, several frames below
    anything the caller wrote. Naming the measure and the backend turns that into an
    answer.

    This refuses rather than substituting the reference. Where the question is about
    the ansatz rather than the device - :func:`~qmlkit.diagnostics.diagnose` - the
    substitution is the right move and the report says so. Here the caller named a
    backend and asked for a measure on it.
    """
    device = get_backend(backend)
    if not device.supports_statevector:
        raise ValueError(
            f"{measure} is defined on a pure state, and the {device.name!r} backend "
            "evolves a density matrix. Run it on a statevector backend to ask about the "
            "ansatz itself; to ask what the noise did to a particular circuit, use that "
            "backend's purity() or density_matrix()."
        )
    return device

default_backend

default_backend() -> Backend

The process-wide default.

NumPy unless QMLKIT_BACKEND says otherwise - exact, always present, and the reference every other backend is tested against.

Source code in src/qmlkit/core/backends/registry.py
def default_backend() -> Backend:
    """The process-wide default.

    NumPy unless ``QMLKIT_BACKEND`` says otherwise - exact, always present, and the
    reference every other backend is tested against.
    """
    global _default
    if _default is None:
        requested = os.environ.get("QMLKIT_BACKEND")
        _default = get_backend(requested) if requested else NumpyBackend()
    return _default

set_default_backend

set_default_backend(
    backend: str | Backend, **kwargs: object
) -> Backend

Set the process-wide default backend and return it.

Source code in src/qmlkit/core/backends/registry.py
def set_default_backend(backend: str | Backend, **kwargs: object) -> Backend:
    """Set the process-wide default backend and return it."""
    global _default
    _default = get_backend(backend, **kwargs)
    return _default

Exact statevector simulators

qmlkit.core.backends.numpy_backend

numpy_backend

Exact statevector simulator — the reference implementation.

This backend is the yardstick every other backend is measured against, and it is what lets the library (and CI) run on Python 3.11+, where SpinQit has no wheel. It is deliberately double-precision throughout: torch.autograd.gradcheck requires float64, and so does any honest claim that parameter-shift is exact.

Sampling, basis rotation and expectation semantics all live in :class:~qmlkit.core.backends.base.Backend; this class supplies the statevector and nothing else.

Convention: qubit 0 is the most significant bit of a bitstring, so basis_encode([1, 0, 1]) yields '101' and reads in the order it was written.

NumpyBackend

NumpyBackend(seed: int | None = None, max_qubits: int = 24)

Bases: Backend

Exact statevector simulation in NumPy.

Source code in src/qmlkit/core/backends/numpy_backend.py
def __init__(self, seed: int | None = None, max_qubits: int = 24) -> None:
    super().__init__(seed)
    self.max_qubits = max_qubits
statevector_batch_slots
statevector_batch_slots(
    spec: CircuitSpec, slot_angles: NDArray[Any]
) -> NDArray[Any]

Every row's state in one pass, batch carried as a leading axis.

The loop is over gates, not over rows: each gate is applied to the whole stack at once. A gate with literal angles contributes one matrix; a parameterised one contributes a stack of them, read straight off the slot columns and built in closed form for the common rotations.

Source code in src/qmlkit/core/backends/numpy_backend.py
def statevector_batch_slots(
    self, spec: CircuitSpec, slot_angles: npt.NDArray[Any]
) -> npt.NDArray[Any]:
    """Every row's state in one pass, batch carried as a leading axis.

    The loop is over *gates*, not over rows: each gate is applied to the whole
    stack at once. A gate with literal angles contributes one matrix; a
    parameterised one contributes a stack of them, read straight off the slot
    columns and built in closed form for the common rotations.
    """
    rows = np.atleast_2d(np.asarray(slot_angles, dtype=float))
    n_slots = len(spec.slots())
    if rows.shape[1] != n_slots:
        raise ValueError(
            f"circuit has {n_slots} slot(s); got vectors of length {rows.shape[1]}"
        )
    if spec.n_qubits > self.max_qubits:
        raise ValueError(
            f"{spec.n_qubits} qubits exceeds max_qubits={self.max_qubits}; "
            "raise it explicitly if you really mean to allocate that much memory"
        )
    if spec.n_qubits > self.batch_max_qubits:
        # wider than the crossover: the one-at-a-time loop is genuinely faster
        return super().statevector_batch_slots(spec, rows)

    batch = rows.shape[0]
    state = np.zeros((batch,) + (2,) * spec.n_qubits, dtype=complex)
    state[(slice(None),) + (0,) * spec.n_qubits] = 1.0

    # slots are ordered by (op_index, param_pos), so walking them in step with the
    # ops keeps the cursor aligned without a lookup per gate
    slots = spec.slots()
    cursor = 0
    for op_index, op in enumerate(spec.ops):
        n_here = 0
        while cursor + n_here < len(slots) and slots[cursor + n_here].op_index == op_index:
            n_here += 1
        columns = rows[:, cursor : cursor + n_here] if n_here else None
        cursor += n_here
        state = _apply_batch(state, _batched_matrices(op, columns), op.qubits)
    return state.reshape(batch, -1)

qmlkit.core.backends.aer_backend

aer_backend

Aer's statevector simulator — the fast Qiskit path.

Qiskit ships two ways to get a statevector and they are not close in cost. qiskit.quantum_info.Statevector is the reference implementation: exact, pure Python and NumPy, and what the qiskit backend uses. AerSimulator is the C++ one. Same answer, very different wall clock, and nothing in the library was reaching the second.

So there are three Qiskit-flavoured backends and it is worth being blunt about which is which:

name simulator for
qiskit quantum_info.Statevector the reference; exact, slow, no extra install
aer AerSimulator(method="statevector") the same answer, faster
qiskit-aer AerSimulator(method="density_matrix") noise; a different question

This class changes only where the amplitudes come from. Circuit translation, qubit order, the matrix fallback that lets a registered gate run here, and every measurement semantic are inherited unchanged from :class:QiskitBackend and the base class — which is what makes "same answer" a property rather than a hope, and is asserted by the cross-backend suite like any other backend.

AerBackend

AerBackend(
    seed: int | None = None,
    max_parallel_experiments: int | None = None,
    device: str = "CPU",
)

Bases: QiskitBackend

Runs qmlkit circuits on AerSimulator(method="statevector").

import qmlkit as qk # doctest: +SKIP qk.expectation(spec, qk.Z(0), backend="aer") # doctest: +SKIP

Source code in src/qmlkit/core/backends/aer_backend.py
def __init__(
    self,
    seed: int | None = None,
    max_parallel_experiments: int | None = None,
    device: str = "CPU",
) -> None:
    super().__init__(seed)
    try:
        from qiskit_aer import AerSimulator
    except ImportError as exc:  # pragma: no cover - depends on the environment
        raise BackendNotAvailable(
            "Qiskit Aer is not installed. It is a separate package from Qiskit:\n"
            "    pip install 'qmlkit[aer]'"
        ) from exc
    # `device="GPU"` needs the separate `qiskit-aer-gpu` distribution, which
    # publishes no Windows wheel - so this path is **untested here** and is a
    # passthrough rather than a claim. Aer reports what it actually has, and
    # asking for a device it does not have should say so rather than silently
    # running on the CPU and looking merely disappointing.
    if device.upper() != "CPU":
        available = AerSimulator().available_devices()
        if device.upper() not in {d.upper() for d in available}:
            raise BackendNotAvailable(
                f"this Aer build has no {device!r} device - it reports {available}. "
                "GPU needs the separate 'qiskit-aer-gpu' distribution, which is "
                "Linux-only; there is no Windows wheel."
            )
    self._simulator = AerSimulator(method="statevector", device=device)
    self._max_parallel = max_parallel_experiments
    self.device = device
statevector_batch_slots
statevector_batch_slots(
    spec: CircuitSpec, slot_angles: NDArray[Any]
) -> NDArray[Any]

Every row in one Aer job.

This override is the whole reason this backend exists. Aer's simulation kernel is C++ and fast; its per-job cost — transpiling, building a job, unpacking a result — is Python and is not. On the circuits this library runs, one job per row makes Aer slower than the pure-Python quantum_info.Statevector it was supposed to beat. Submitting the whole batch as one job is what turns that around, and it is also exactly the shape a real provider wants.

Source code in src/qmlkit/core/backends/aer_backend.py
def statevector_batch_slots(
    self, spec: CircuitSpec, slot_angles: npt.NDArray[Any]
) -> npt.NDArray[Any]:
    """Every row in **one** Aer job.

    This override is the whole reason this backend exists. Aer's simulation kernel
    is C++ and fast; its *per-job* cost — transpiling, building a job, unpacking a
    result — is Python and is not. On the circuits this library runs, one job per
    row makes Aer slower than the pure-Python ``quantum_info.Statevector`` it was
    supposed to beat. Submitting the whole batch as one job is what turns that
    around, and it is also exactly the shape a real provider wants.
    """
    from qmlkit.progress import task as progress_task

    rows = np.atleast_2d(np.asarray(slot_angles, dtype=float))
    with progress_task(f"{self.name} circuits", len(rows)) as tracked:
        circuits = []
        for row in rows:
            circuits.append(self._prepared(spec.with_slot_angles(row)))
            tracked.advance()
        result = self._simulator.run(
            circuits, max_parallel_experiments=self._parallel_for(spec.n_qubits)
        ).result()
    return np.stack(
        [np.asarray(result.get_statevector(i), dtype=complex) for i in range(len(rows))]
    )

qmlkit.core.backends.qiskit_backend

qiskit_backend

Qiskit backend.

Endianness. Qiskit is little-endian: its statevector index puts qubit 0 in the least significant bit, while qmlkit puts it in the most significant. Rather than reversing vectors after the fact — easy to get right once and wrong forever after — we map qmlkit qubit i onto Qiskit qubit n-1-i when building the circuit. The two index conventions then coincide exactly, and Qiskit's own bitstring keys come out in qmlkit order with no post-processing.

Every gate convention here is verified against the NumPy backend by tests/test_cross_backend.py rather than assumed.

QiskitBackend

QiskitBackend(seed: int | None = None)

Bases: Backend

Runs qmlkit circuits on Qiskit's reference statevector simulator.

Source code in src/qmlkit/core/backends/qiskit_backend.py
def __init__(self, seed: int | None = None) -> None:
    super().__init__(seed)
    try:
        import qiskit  # noqa: F401
        from qiskit.quantum_info import Statevector
    except ImportError as exc:  # pragma: no cover - depends on the environment
        raise BackendNotAvailable(
            "Qiskit is not installed. Install it with:\n    pip install 'qmlkit[qiskit]'"
        ) from exc
    self._Statevector = Statevector
to_qiskit
to_qiskit(spec: CircuitSpec) -> QuantumCircuit

Translate a bound :class:CircuitSpec into a Qiskit circuit.

Public because an idiomatic Qiskit circuit is useful in its own right — draw it, transpile it, or send it to a provider.

Source code in src/qmlkit/core/backends/qiskit_backend.py
def to_qiskit(self, spec: CircuitSpec) -> QuantumCircuit:
    """Translate a bound :class:`CircuitSpec` into a Qiskit circuit.

    Public because an idiomatic Qiskit circuit is useful in its own right —
    draw it, transpile it, or send it to a provider.
    """
    from qiskit import QuantumCircuit

    self._check_bound(spec)
    n = spec.n_qubits
    qc = QuantumCircuit(n)

    for op in spec.ops:
        angles = [self._angle(p, op.gate) for p in op.params]
        wires = [n - 1 - q for q in op.qubits]  # qmlkit qubit -> qiskit qubit
        method = _GATE_METHODS.get(op.gate)
        if method is not None:
            getattr(qc, method)(*angles, *wires)
        else:
            qc.append(self._as_unitary(op.gate, angles), wires)
    return qc

qmlkit.core.backends.cirq_backend

cirq_backend

Cirq backend.

Endianness. Cirq orders its statevector by the given qubit_order, first qubit most significant — which is already qmlkit's convention. Mapping qmlkit qubit i to LineQubit(i) and passing an explicit ascending order needs no index gymnastics, but the explicit order is required: without it Cirq drops qubits the circuit never touches and silently returns a shorter vector.

Every gate convention here is verified against the NumPy backend by tests/test_cross_backend.py rather than assumed.

CirqBackend

CirqBackend(seed: int | None = None)

Bases: Backend

Runs qmlkit circuits on cirq.Simulator.

Source code in src/qmlkit/core/backends/cirq_backend.py
def __init__(self, seed: int | None = None) -> None:
    super().__init__(seed)
    try:
        import cirq
    except ImportError as exc:  # pragma: no cover - depends on the environment
        raise BackendNotAvailable(
            "Cirq is not installed. Install it with:\n    pip install 'qmlkit[cirq]'"
        ) from exc
    self._cirq = cirq
    self._factories = _gate_factories()
    # complex128 keeps the reference comparison honest; Cirq defaults to complex64
    self._simulator = cirq.Simulator(dtype=np.complex128)
to_cirq
to_cirq(spec: CircuitSpec) -> Circuit

Translate a bound :class:CircuitSpec into a Cirq circuit.

Source code in src/qmlkit/core/backends/cirq_backend.py
def to_cirq(self, spec: CircuitSpec) -> cirq.Circuit:
    """Translate a bound :class:`CircuitSpec` into a Cirq circuit."""
    self._check_bound(spec)
    cirq = self._cirq
    qubits = self.qubits(spec.n_qubits)
    moments = []
    for op in spec.ops:
        angles = [self._angle(p, op.gate) for p in op.params]
        factory = self._factories.get(op.gate)
        if factory is not None:
            gate = factory(*angles)
        else:
            gate = self._as_matrix_gate(op.gate, angles)
        moments.append(gate.on(*[qubits[q] for q in op.qubits]))
    return cirq.Circuit(moments)

qmlkit.core.backends.openqarp_backend

The one statevector backend here that does not stop at the statevector: it contracts expectations inside OpenQARP's C++ kernel and sweeps a batch of parameter vectors in one call. That is two derived quantities computed by an SDK rather than by base.py, so both are pinned against the NumPy reference — and native_expectations=False asks the same backend for the other route. Integrating OpenQARP walks through the translation and the measurements; scripts/probe_openqarp.py reproduces them.

openqarp_backend

OpenQARP backend.

Fujitsu's Open Quantum Application Research Package: a Python framework over a compiled C++ core, in which blocks describe circuits, primitives say what to read off them, and engines say how they run. This backend takes the engine directly -- qarpx.QarpSimulator -- and with it the two entry points no other backend here offers: an expectation contracted inside the simulator without ever materialising the statevector, and that same expectation swept over a list of parameter sets without coming back to Python between rows.

Endianness. qarp indexes amplitudes LSB-first: qubit q carries bit q, which is the opposite of qmlkit. The handling is the Qiskit backend's, for the Qiskit backend's reason -- qmlkit qubit i is mapped onto qarp qubit n-1-i at build time, so the two index conventions coincide and nothing downstream reverses anything. Reversing the vector afterwards would also have been the slower of the two: qarp.endianness.lsb_to_msb_statevector builds its permutation from a Python loop over 2**n formatted strings, which costs 40 ms at 16 qubits -- four times the 11 ms simulation it would be decorating.

What is overridden, and why. statevector is the primitive, as everywhere else. Two derived quantities are overridden as well, and both hand this library's observable to an SDK instead of deriving it in :mod:qmlkit.core.backends.base -- the same exception the MPS backend makes, and the reason both are pinned against the NumPy reference in tests/test_cross_backend.py rather than argued for here.

:meth:~OpenQARPBackend.expectation contracted in C++ from a state that is never returned, and no 2**n array to hold: 0.39 ms against 0.54 at ten qubits, 0.91 against 1.09 at twelve, 2.77 against 3.45 at fourteen, and the two converge by sixteen.

:meth:~OpenQARPBackend.expectation_over_slots the reason to reach for this SDK at all. One sweep instead of a translation per row: 256 rows of a three-layer ry/rz ring at ten qubits take 37 ms here, against 237 ms on the NumPy reference and 666 ms on Aer. A batched parameter-shift gradient and every forward pass of QuantumLayer are made of exactly this call -- an adjoint gradient and a Gram matrix are not, and ask for statevectors instead, where this backend is ordinary. Against its own row-by-row path the sweep is 6.5x at eight qubits and 1.2x at fourteen, bit-identical at both.

native_expectations=False takes both away and derives expectations from the statevector like every other backend. That is not a fallback for when something breaks; it is how the suite asks one backend the same question by two routes that share no arithmetic, and compares the answers.

(Every number here comes out of scripts/probe_openqarp.py, on one machine -- Windows, Python 3.14, OpenQARP 0.1.0. Run it on yours; the ratios travel, the milliseconds do not. docs/guides/openqarp.md is the long form.)

OpenQARPBackend

OpenQARPBackend(
    seed: int | None = None,
    native_expectations: bool = True,
)

Bases: Backend

Runs qmlkit circuits on OpenQARP's QarpSimulator.

Source code in src/qmlkit/core/backends/openqarp_backend.py
def __init__(self, seed: int | None = None, native_expectations: bool = True) -> None:
    super().__init__(seed)
    try:
        import qarpx
        from qarp.blocks import CompositeBlock, SimpleBlock, SynthesizedUnitaryBlock
    except ImportError as exc:  # pragma: no cover - depends on the environment
        raise BackendNotAvailable(
            "OpenQARP is not installed. Install it with:\n"
            "    pip install 'qmlkit[openqarp]'\n"
            "(the distribution is 'openqarp'; the module it installs is 'qarp')"
        ) from exc
    self._qx = qarpx
    self._SimpleBlock = SimpleBlock
    self._CompositeBlock = CompositeBlock
    self._SynthesizedUnitaryBlock = SynthesizedUnitaryBlock
    self._native = bool(native_expectations)
to_openqarp
to_openqarp(spec: CircuitSpec) -> Block

Translate a bound :class:CircuitSpec into a qarp block.

Source code in src/qmlkit/core/backends/openqarp_backend.py
def to_openqarp(self, spec: CircuitSpec) -> qarpx.Block:
    """Translate a bound :class:`CircuitSpec` into a qarp block."""
    self._check_bound(spec)
    return self._emit(spec, symbolic=False)
expectation
expectation(
    spec: CircuitSpec,
    obs: Observable,
    shots: int | None = None,
    seed: int | None = None,
) -> float

<O>, contracted inside the simulator when it may be.

Source code in src/qmlkit/core/backends/openqarp_backend.py
def expectation(
    self,
    spec: CircuitSpec,
    obs: Observable,
    shots: int | None = None,
    seed: int | None = None,
) -> float:
    """``<O>``, contracted inside the simulator when it may be."""
    self._check_bound(spec)
    if not self._contracts(obs, shots):
        return super().expectation(spec, obs, shots, seed)
    commands = self._emit(spec, symbolic=False).flatten()
    value = self._qx.QarpSimulator().expectation(
        commands, spec.n_qubits, self._terms(obs, spec.n_qubits)
    )
    return float(value)
expectation_over_slots
expectation_over_slots(
    spec: CircuitSpec,
    slot_angles: NDArray[Any],
    obs: Observable,
    shots: int | None = None,
    seed: int | None = None,
) -> NDArray[Any]

<O> at many slot-angle vectors, as one C++ sweep per chunk.

The circuit is translated once, with a symbol at every slot, and the rows are bound inside the kernel. That is the difference between paying for the translation once and paying for it per row, and at the widths quantum machine learning actually runs at the translation is most of the bill: 7.4x at eight qubits, 1.7x at twelve, 1.2x at fourteen -- and the same numbers to the last bit, because it is the same circuit either way.

Source code in src/qmlkit/core/backends/openqarp_backend.py
def expectation_over_slots(
    self,
    spec: CircuitSpec,
    slot_angles: npt.NDArray[Any],
    obs: Observable,
    shots: int | None = None,
    seed: int | None = None,
) -> npt.NDArray[Any]:
    """``<O>`` at many slot-angle vectors, as one C++ sweep per chunk.

    The circuit is translated **once**, with a symbol at every slot, and the rows
    are bound inside the kernel. That is the difference between paying for the
    translation once and paying for it per row, and at the widths quantum machine
    learning actually runs at the translation is most of the bill: 7.4x at eight
    qubits, 1.7x at twelve, 1.2x at fourteen -- and the same numbers to the last
    bit, because it is the same circuit either way.
    """
    rows = np.atleast_2d(np.asarray(slot_angles, dtype=float))
    if not self._contracts(obs, shots) or not self._sweepable(spec):
        return super().expectation_over_slots(spec, rows, obs, shots, seed)

    n_slots = len(spec.slots())
    if rows.shape[1] != n_slots:
        raise ValueError(f"expected {n_slots} slot angles, got {rows.shape[1]}")

    from qmlkit.progress import task as progress_task

    commands = self._emit(spec, symbolic=True).flatten()
    terms = self._terms(obs, spec.n_qubits)
    names = [_SLOT_SYMBOL.format(k) for k in range(n_slots)]
    simulator = self._qx.QarpSimulator()

    out = np.empty(rows.shape[0], dtype=float)
    with progress_task(f"{self.name} circuits", rows.shape[0]) as tracked:
        for start in range(0, rows.shape[0], self.sweep_rows):
            chunk = rows[start : start + self.sweep_rows]
            bindings = [dict(zip(names, map(float, row), strict=True)) for row in chunk]
            out[start : start + chunk.shape[0]] = simulator.batch_expectation(
                commands, spec.n_qubits, terms, bindings
            )
            tracked.advance(chunk.shape[0])
    return out

qmlkit.core.backends.spinqit_backend

spinqit_backend

SpinQit backend.

Verified against a live SpinQit install (Python 3.10). The conventions that matter, all confirmed empirically rather than assumed:

  • Bit order matches qmlkit. X on qubit 0 of a two-qubit register yields {'10': shots} — qubit 0 is the most significant bit. No remapping needed, unlike Qiskit.
  • result.states is an exact complex128 statevector, so SpinQit supports an exact mode; it is not sampling-only.
  • result.probabilities is a dict keyed by bitstring, not an array.
  • ControlledGate(Rz) reproduces qmlkit's crz exactly, and P, Sd and Td match phase, sdg and tdg.
  • Shots are configured with config.configure_shots(n). There is no with_shots; Circuit.measure takes (qubits, clbits), not one argument.

By default sampling goes through qmlkit's shared seeded sampler so results are reproducible and comparable with the other backends. Pass native_sampling=True to let SpinQit draw the shots itself, which is what you want when the point is to model the device rather than to compare backends.

SpinQitBackend

SpinQitBackend(
    seed: int | None = None,
    compiler: str = "native",
    native_sampling: bool = False,
)

Bases: Backend

Runs qmlkit circuits on SpinQit's simulator.

Source code in src/qmlkit/core/backends/spinqit_backend.py
def __init__(
    self,
    seed: int | None = None,
    compiler: str = "native",
    native_sampling: bool = False,
) -> None:
    super().__init__(seed)
    try:
        import spinqit  # noqa: F401
        from spinqit import BasicSimulatorConfig, get_basic_simulator, get_compiler
    except ImportError as exc:  # pragma: no cover - depends on the environment
        raise BackendNotAvailable(
            "SpinQit is not installed or not importable in this interpreter.\n"
            "It ships wheels for Python 3.8-3.10 only and pins numpy<2:\n"
            "    pip install 'qmlkit[spinqit]'   # on a 3.8-3.10 interpreter\n"
            "The 'numpy' backend is exact and works on every supported Python."
        ) from exc
    self._compiler_name = compiler
    self._compiler = get_compiler(compiler)
    self._engine = get_basic_simulator()
    self._config_cls = BasicSimulatorConfig
    self._gates = _gate_table()
    self.native_sampling = native_sampling
to_spinqit
to_spinqit(spec: CircuitSpec) -> Any

Translate a bound :class:CircuitSpec into a SpinQit Circuit.

Public because an idiomatic SpinQit circuit is useful on its own — draw it, or hand it to SpinQit's own algorithms.

Source code in src/qmlkit/core/backends/spinqit_backend.py
def to_spinqit(self, spec: CircuitSpec) -> Any:
    """Translate a bound :class:`CircuitSpec` into a SpinQit ``Circuit``.

    Public because an idiomatic SpinQit circuit is useful on its own — draw it,
    or hand it to SpinQit's own algorithms.
    """
    from spinqit import Circuit

    self._check_bound(spec)
    circ = Circuit()
    q = circ.allocateQubits(spec.n_qubits)

    for op in spec.ops:
        if op.gate in _DECOMPOSITIONS:
            for sub_gate, sub_pos in _DECOMPOSITIONS[op.gate]:
                sub_qubits = tuple(op.qubits[i] for i in sub_pos)
                self._emit(circ, q, sub_gate, sub_qubits, ())
            continue
        angles = tuple(self._angle(p, op.gate) for p in op.params)
        self._emit(circ, q, op.gate, op.qubits, angles)
    return circ
counts
counts(
    spec: CircuitSpec, shots: int, seed: int | None = None
) -> dict[str, int]

Sample the computational basis.

Uses qmlkit's shared seeded sampler by default so runs are reproducible and directly comparable with the other backends. native_sampling=True hands the job to SpinQit instead, which is unseeded but models the device.

Source code in src/qmlkit/core/backends/spinqit_backend.py
def counts(self, spec: CircuitSpec, shots: int, seed: int | None = None) -> dict[str, int]:
    """Sample the computational basis.

    Uses qmlkit's shared seeded sampler by default so runs are reproducible and
    directly comparable with the other backends. ``native_sampling=True`` hands
    the job to SpinQit instead, which is unseeded but models the device.
    """
    if not self.native_sampling:
        return super().counts(spec, shots, seed)
    self._check_bound(spec)
    if shots <= 0:
        raise ValueError("shots must be positive")
    raw = self._execute(spec, shots).counts
    width = spec.n_qubits
    return {str(k).zfill(width): int(v) for k, v in raw.items()}
verify_conventions
verify_conventions() -> dict[str, bool]

Check this install against the conventions the backend assumes.

Cheap insurance against a SpinQit release quietly changing bit order or a gate definition. Returns a name -> passed mapping; all values should be True.

Source code in src/qmlkit/core/backends/spinqit_backend.py
def verify_conventions(self) -> dict[str, bool]:
    """Check this install against the conventions the backend assumes.

    Cheap insurance against a SpinQit release quietly changing bit order or a
    gate definition. Returns a name -> passed mapping; all values should be True.
    """
    from qmlkit.core.builder import QCircuit

    results: dict[str, bool] = {}

    qc = QCircuit(2)
    qc.x(0)
    probs = np.abs(self.statevector(qc.to_spec())) ** 2
    results["qubit0_is_most_significant"] = bool(np.argmax(probs) == 0b10)

    qc = QCircuit(1)
    qc.ry(0, 0.7)
    psi = self.statevector(qc.to_spec())
    results["ry_is_exp_minus_i_theta_y_over_2"] = bool(
        np.allclose(psi, [np.cos(0.35), np.sin(0.35)], atol=1e-9)
    )

    qc = QCircuit(2)
    qc.x(0).crz(0, 1, 0.7)
    psi = self.statevector(qc.to_spec())
    results["controlled_rz_matches"] = bool(
        np.isclose(psi[0b10], np.exp(-1j * 0.35), atol=1e-9)
    )

    qc = QCircuit(1)
    qc.x(0).phase(0, 0.7)
    psi = self.statevector(qc.to_spec())
    results["phase_is_diag_1_expi_theta"] = bool(
        np.isclose(psi[1], np.exp(1j * 0.7), atol=1e-9)
    )
    qc = QCircuit(2)
    qc.h(0).cy(0, 1)
    psi = self.statevector(qc.to_spec())
    expected = np.array([1, 0, 0, 1j]) / np.sqrt(2)
    results["controlled_y_matches"] = bool(np.allclose(psi, expected, atol=1e-8))

    return results

Differentiable

qmlkit.core.backends.torch_backend

torch_backend

Differentiable statevector simulator in PyTorch.

Every gate is built from torch tensors, so the whole circuit sits inside autograd's graph and backward() differentiates it directly. That is backpropagation — the fastest gradient available on a simulator, and the one PennyLane reaches for by default on default.qubit.

It is also the least physical. Backprop reads intermediate states that no device will ever expose, and its memory grows with circuit depth because every intermediate is retained. Adjoint gets the same exact answer at constant memory; parameter-shift gets it from measurements alone. This backend is here because it is fast and because it makes method="backprop" a real option, not because it could ever run anywhere but a simulator.

TorchBackend

TorchBackend(seed: int | None = None)

Bases: Backend

Statevector simulation in torch — differentiable end to end.

Source code in src/qmlkit/core/backends/torch_backend.py
def __init__(self, seed: int | None = None) -> None:
    super().__init__(seed)
    try:
        import torch
    except ImportError as exc:  # pragma: no cover - depends on the environment
        raise BackendNotAvailable(
            "the torch backend needs PyTorch:\n    pip install 'qmlkit[torch]'"
        ) from exc
    self._torch = torch
expectation_tensor
expectation_tensor(
    spec: CircuitSpec,
    theta: Any,
    obs: Observable | None = None,
) -> Any

The differentiable path — returns a torch scalar, not a float.

Source code in src/qmlkit/core/backends/torch_backend.py
def expectation_tensor(
    self, spec: CircuitSpec, theta: Any, obs: Observable | None = None
) -> Any:
    """The differentiable path — returns a torch scalar, not a float."""
    return torch_expectation(spec, theta, obs)

torch_expectation

torch_expectation(
    spec: CircuitSpec,
    theta: Any,
    obs: Observable | None = None,
) -> Any

<obs> as a torch scalar, differentiable through theta.

Source code in src/qmlkit/core/backends/torch_backend.py
def torch_expectation(spec: CircuitSpec, theta: Any, obs: Observable | None = None) -> Any:
    """``<obs>`` as a torch scalar, differentiable through ``theta``."""
    try:
        import torch
    except ImportError as exc:  # pragma: no cover - depends on the environment
        raise BackendNotAvailable(
            "the torch backend needs PyTorch:\n    pip install 'qmlkit[torch]'"
        ) from exc

    obs = Z(0) if obs is None else obs
    n = spec.n_qubits
    if not torch.is_tensor(theta):
        theta = torch.tensor(np.asarray(theta, dtype=float), dtype=torch.float64)

    slot_angles = []
    for slot in spec.slots():
        ref = slot.ref
        slot_angles.append(ref.scale * theta[ref.index] + ref.offset)

    state = torch.zeros((2,) * n, dtype=torch.complex128)
    state[(0,) * n] = 1.0

    cursor = 0
    for op in spec.ops:
        angles: list[Any] = []
        for p in op.params:
            if isinstance(p, ParamRef):
                angles.append(slot_angles[cursor])
                cursor += 1
            else:
                angles.append(float(p))
        state = _apply_torch(torch, state, _gate_tensor(torch, op.gate, angles), op.qubits)

    flat = state.reshape(-1)
    total = torch.zeros((), dtype=torch.complex128)
    for term in as_sum(obs).terms:
        out = state
        for qubit, pauli in term.paulis:
            if pauli == "I":
                continue
            out = _apply_torch(torch, out, _gate_tensor(torch, pauli.lower(), []), (qubit,))
        total = total + term.coeff * torch.sum(torch.conj(flat) * out.reshape(-1))
    return torch.real(total)

Approximate

qmlkit.core.backends.mps_backend

A matrix-product-state simulator reaches widths a statevector cannot, by keeping only as much entanglement as its bond dimension allows. It has no statevector(), so every route that needs one is refused rather than approximated; and past the bond dimension it is no longer exact, which is a different thing from noisy.

mps_backend

Aer's matrix-product-state simulator — width, at the price of entanglement.

Every other backend here stores 2**n amplitudes, which is why 30 qubits is out of reach: the array alone is 16 GiB. An MPS stores the state as a chain of small tensors and only grows when the circuit entangles, so a lightly entangled circuit stays cheap at widths a statevector cannot reach at all.

Measured, a linear chain of ry + nearest-neighbour cx, asking for one expectation:

qubits statevector MPS
20 0.013 s 0.001 s
24 0.279 s 0.002 s
28 4.97 s 0.002 s
32 fails — needs 65 GiB 0.002 s

This backend has no statevector, and that is the point. Asking an MPS for all 2**n amplitudes contracts the whole network and throws away everything it was doing for you — measured 13.6 s against 0.26 s at 24 qubits, fifty times slower than the statevector simulator it was meant to beat. So supports_statevector is false: adjoint and backprop refuse rather than quietly costing more than they save, and parameter-shift works, because a shift rule never inspects a state.

It is exact only while the entanglement stays inside the bond dimension. Beyond that Aer truncates, and the answer is an approximation that does not announce itself. A hardware-efficient ansatz with a full entangler ring is the worst case for this and a chain-structured or shallow circuit is the best; :meth:bond_dimension reports what the run actually needed, so the question can be answered rather than assumed.

MPSBackend

MPSBackend(
    seed: int | None = None,
    max_bond_dimension: int | None = None,
)

Bases: QiskitBackend

Runs qmlkit circuits on AerSimulator(method="matrix_product_state").

import qmlkit as qk # doctest: +SKIP qk.expectation(spec, qk.Z(0), backend="mps") # doctest: +SKIP

Source code in src/qmlkit/core/backends/mps_backend.py
def __init__(self, seed: int | None = None, max_bond_dimension: int | None = None) -> None:
    super().__init__(seed)
    try:
        from qiskit_aer import AerSimulator
    except ImportError as exc:  # pragma: no cover - depends on the environment
        raise BackendNotAvailable(
            "Qiskit Aer is not installed. It is a separate package from Qiskit:\n"
            "    pip install 'qmlkit[aer]'"
        ) from exc
    options: dict[str, Any] = {"method": "matrix_product_state"}
    if max_bond_dimension is not None:
        # Capping the bond is the one setting here that turns an exact simulator
        # into an approximate one, and it does it silently: measured on a 12-qubit
        # hardware-efficient ansatz, capping at 4 moved the expectation from
        # 1.4154454301 to 1.4512716722 with nothing raised and the answer still in
        # range. That is the failure this library exists to refuse, so it is said
        # out loud at the moment the caller asks for it.
        warnings.warn(
            f"max_bond_dimension={max_bond_dimension} makes this backend "
            "APPROXIMATE: once a circuit entangles past that bond, Aer truncates "
            "and the expectation is wrong without anything raising (measured 3.6e-2 "
            "off on a 12-qubit hardware-efficient ansatz at bond 4). Check what a "
            "run actually needed with MPSBackend.bond_dimension(spec), or leave it "
            "unset and let the bond grow.",
            RuntimeWarning,
            stacklevel=2,
        )
        options["matrix_product_state_max_bond_dimension"] = max_bond_dimension
    self._simulator = AerSimulator(**options)
    self.max_bond_dimension = max_bond_dimension
statevector
statevector(spec: CircuitSpec) -> NDArray[Any]

Always refuses, and the refusal is the feature.

Contracting the network to 2**n amplitudes discards the representation that makes this backend worth having: measured 13.6 s against 0.26 s at 24 qubits, and impossible at 32. A backend that answered here would look correct and be pointless, which is the harder failure to notice.

Source code in src/qmlkit/core/backends/mps_backend.py
def statevector(self, spec: CircuitSpec) -> npt.NDArray[Any]:
    """Always refuses, and the refusal is the feature.

    Contracting the network to ``2**n`` amplitudes discards the representation
    that makes this backend worth having: measured 13.6 s against 0.26 s at 24
    qubits, and impossible at 32. A backend that answered here would look correct
    and be pointless, which is the harder failure to notice.
    """
    raise NotImplementedError(
        f"the {self.name!r} backend has no statevector - materialising 2**"
        f"{spec.n_qubits} amplitudes is exactly what a matrix product state avoids, "
        "and doing it is slower than using the 'aer' backend in the first place. "
        "Ask for an expectation instead, or use backend='aer'."
    )
expectation
expectation(
    spec: CircuitSpec,
    obs: Observable,
    shots: int | None = None,
    seed: int | None = None,
) -> float

<O> computed inside the MPS, without ever forming a statevector.

Source code in src/qmlkit/core/backends/mps_backend.py
def expectation(
    self,
    spec: CircuitSpec,
    obs: Observable,
    shots: int | None = None,
    seed: int | None = None,
) -> float:
    """``<O>`` computed inside the MPS, without ever forming a statevector."""
    self._check_bound(spec)
    if shots is not None:
        return super().expectation(spec, obs, shots, seed)

    from qiskit.quantum_info import SparsePauliOp

    total = as_sum(obs)
    terms = [(self._pauli_string(t, spec.n_qubits), complex(t.coeff)) for t in total.terms]
    operator = SparsePauliOp.from_list(terms)

    circuit = self._prepared(spec)
    circuit.save_expectation_value(operator, range(spec.n_qubits))
    result = self._simulator.run(circuit).result()
    value = float(np.real(result.data(0)["expectation_value"]))
    return value
bond_dimension
bond_dimension(spec: CircuitSpec) -> int

The largest bond the circuit actually needed.

The number that says whether this run was exact. An MPS is exact while the bond dimension is allowed to grow to what the entanglement demands; once Aer truncates, the answer is an approximation and nothing about it looks different.

Source code in src/qmlkit/core/backends/mps_backend.py
def bond_dimension(self, spec: CircuitSpec) -> int:
    """The largest bond the circuit actually needed.

    The number that says whether this run was exact. An MPS is exact while the
    bond dimension is allowed to grow to what the entanglement demands; once Aer
    truncates, the answer is an approximation and nothing about it looks different.
    """
    circuit = self._prepared(spec)
    circuit.save_matrix_product_state()
    result = self._simulator.run(circuit).result()
    state = result.data(0)["matrix_product_state"]
    return max((len(lam) for lam in state[1]), default=1)

Mixed-state, for noise

qmlkit.core.backends.noisy

noisy

Mixed-state backends, where the noise model is the point.

A noisy backend is a normal backend with one primitive swapped: it has a density matrix instead of a statevector. Everything above that - basis rotation, qubit-wise commuting groups, sampling, expectation values - is inherited unchanged, so a noisy run and an exact one differ in the number they produce and in nothing else.

Two capability flags do the work, and they are not the same flag.

supports_statevector is false: there is no pure state, so adjoint and backprop refuse rather than quietly differentiating a noiseless circuit and handing back a machine-precision number to someone who asked about a noisy one. Parameter-shift keeps working, because a shift rule never inspects a state.

supports_exact stays true, which is the part worth being deliberate about. A density-matrix simulator can give a shot-free expectation - exact given the noise model - and that separates the two error sources that otherwise arrive together. Studying decoherence with shot noise layered on top means never knowing which one you are looking at. Ask for shots=N when you want both.

Nothing here selects a backend for you. Noise is an argument to a named backend, so the choice of simulator is always written down in the code that used it.

NoisyBackend

NoisyBackend(seed: int | None = None)

Bases: Backend

Base for backends that evolve a density matrix rather than a state.

Subclasses implement :meth:density_matrix. Probabilities come from its diagonal, and every other semantic is the base class's.

Source code in src/qmlkit/core/backends/base.py
def __init__(self, seed: int | None = None) -> None:
    self._rng = np.random.default_rng(seed)
density_matrix
density_matrix(spec: CircuitSpec) -> NDArray[Any]

Final state as a (2**n, 2**n) density matrix, qubit 0 most significant.

Source code in src/qmlkit/core/backends/noisy.py
def density_matrix(self, spec: CircuitSpec) -> npt.NDArray[Any]:
    """Final state as a ``(2**n, 2**n)`` density matrix, qubit 0 most significant."""
    raise NotImplementedError(f"the {self.name!r} backend must implement density_matrix()")
statevector
statevector(spec: CircuitSpec) -> NDArray[Any]

Always refuses. A mixed state is not a vector.

Returning the noiseless statevector here would be the plausible-wrong-number failure this library exists to refuse: it would run, agree with the exact backend to machine precision, and answer a question nobody asked.

Source code in src/qmlkit/core/backends/noisy.py
def statevector(self, spec: CircuitSpec) -> npt.NDArray[Any]:
    """Always refuses. A mixed state is not a vector.

    Returning the noiseless statevector here would be the plausible-wrong-number
    failure this library exists to refuse: it would run, agree with the exact
    backend to machine precision, and answer a question nobody asked.
    """
    raise NotImplementedError(
        f"the {self.name!r} backend evolves a density matrix and has no statevector. "
        "Use density_matrix(spec), or probabilities(spec); for gradients use "
        'method="parameter-shift", which is measurement-only.'
    )
probabilities
probabilities(spec: CircuitSpec) -> NDArray[Any]

Outcome probabilities: the real diagonal of the density matrix.

Source code in src/qmlkit/core/backends/noisy.py
def probabilities(self, spec: CircuitSpec) -> npt.NDArray[Any]:
    """Outcome probabilities: the real diagonal of the density matrix."""
    rho = np.asarray(self.density_matrix(spec))
    probs = np.real(np.diagonal(rho)).astype(float)
    # a physical rho has a non-negative diagonal summing to 1; simulators drift by
    # ~1e-16 and a negative probability would poison sampling downstream
    probs = np.clip(probs, 0.0, None)
    total = probs.sum()
    if total <= 0:  # pragma: no cover - defensive
        raise ValueError(f"the {self.name!r} backend returned a density matrix with zero trace")
    normalised: npt.NDArray[Any] = probs / total
    return normalised
purity
purity(spec: CircuitSpec) -> float

Tr(rho^2) - 1 for a pure state, 1/2**n for the maximally mixed one.

The cheapest single number that says how much the noise model actually did.

Source code in src/qmlkit/core/backends/noisy.py
def purity(self, spec: CircuitSpec) -> float:
    """``Tr(rho^2)`` - 1 for a pure state, ``1/2**n`` for the maximally mixed one.

    The cheapest single number that says how much the noise model actually did.
    """
    rho = np.asarray(self.density_matrix(spec))
    return float(np.real(np.trace(rho @ rho)))

qmlkit.core.backends.cirq_density_backend

cirq_density_backend

Cirq's density-matrix simulator, with a noise model.

The circuit translation is :class:~qmlkit.core.backends.cirq_backend.CirqBackend's, unchanged and inherited - a second copy of the gate table is exactly the kind of divergence the cross-backend suite exists to catch. Only the simulator differs.

CirqDensityBackend

CirqDensityBackend(
    seed: int | None = None, noise: Any = None
)

Bases: NoisyBackend, CirqBackend

Runs qmlkit circuits on cirq.DensityMatrixSimulator.

noise is anything Cirq accepts as a NOISE_MODEL_LIKE: a single-qubit channel (applied after every moment, on every qubit), a full cirq.NoiseModel, or None.

None is not a pointless case - it is an exact mixed-state simulator that must agree with the pure-state backends to machine precision, which is what makes the noisy results trustworthy. tests/test_noisy_backends.py asserts exactly that.

import cirq, qmlkit as qk # doctest: +SKIP be = qk.get_backend("cirq-density", noise=cirq.depolarize(0.01)) # doctest: +SKIP qk.expectation(spec, qk.Z(0), backend=be) # doctest: +SKIP

Source code in src/qmlkit/core/backends/cirq_density_backend.py
def __init__(self, seed: int | None = None, noise: Any = None) -> None:
    super().__init__(seed)
    try:
        self._simulator = self._cirq.DensityMatrixSimulator(dtype=np.complex128, noise=noise)
    except (TypeError, ValueError) as exc:
        raise BackendNotAvailable(
            f"cirq could not build a noise model from {noise!r}.\n"
            "Pass a cirq channel (cirq.depolarize(0.01), cirq.amplitude_damp(0.05)), "
            "a cirq.NoiseModel, or None for an exact mixed-state simulation."
        ) from exc
    self.noise = noise
to_cirq
to_cirq(spec: CircuitSpec) -> Circuit

The same translation the pure-state backend uses; noise is applied by the simulator, not written into the circuit.

Source code in src/qmlkit/core/backends/cirq_density_backend.py
def to_cirq(self, spec: CircuitSpec) -> cirq.Circuit:
    """The same translation the pure-state backend uses; noise is applied by the
    simulator, not written into the circuit."""
    return super().to_cirq(spec)

qmlkit.core.backends.qiskit_aer_backend

qiskit_aer_backend

Qiskit Aer's density-matrix simulator, with a noise model.

The circuit translation is :class:~qmlkit.core.backends.qiskit_backend.QiskitBackend's, inherited unchanged - including the qubit remap that makes Qiskit's little-endian index agree with qmlkit's, which is the part an independent second copy would get wrong.

qiskit-aer is a separate distribution from qiskit: installing the Qiskit backend does not give you this one.

QiskitAerBackend

QiskitAerBackend(
    seed: int | None = None, noise: Any = None
)

Bases: NoisyBackend, QiskitBackend

Runs qmlkit circuits on AerSimulator(method="density_matrix").

noise takes a qiskit_aer.noise.NoiseModel - built by hand, or lifted off a real device with NoiseModel.from_backend(...) - or None for an exact mixed-state simulation.

None is the case that keeps the rest honest: it must reproduce the pure-state backends to machine precision, and tests/test_noisy_backends.py asserts it.

from qiskit_aer.noise import NoiseModel, depolarizing_error # doctest: +SKIP nm = NoiseModel() # doctest: +SKIP nm.add_all_qubit_quantum_error(depolarizing_error(0.01, 1), ["rx", "ry", "rz"]) ... # doctest: +SKIP be = qk.get_backend("qiskit-aer", noise=nm) # doctest: +SKIP

Source code in src/qmlkit/core/backends/qiskit_aer_backend.py
def __init__(self, seed: int | None = None, noise: Any = None) -> None:
    super().__init__(seed)
    try:
        from qiskit_aer import AerSimulator
    except ImportError as exc:  # pragma: no cover - depends on the environment
        raise BackendNotAvailable(
            "Qiskit Aer is not installed. It is a separate package from Qiskit:\n"
            "    pip install 'qmlkit[aer]'"
        ) from exc
    self._simulator = AerSimulator(method="density_matrix", noise_model=noise)
    self.noise = noise
to_qiskit
to_qiskit(spec: CircuitSpec) -> QuantumCircuit

The same translation the pure-state backend uses; noise is attached by the simulator, not written into the circuit.

Source code in src/qmlkit/core/backends/qiskit_aer_backend.py
def to_qiskit(self, spec: CircuitSpec) -> QuantumCircuit:
    """The same translation the pure-state backend uses; noise is attached by the
    simulator, not written into the circuit."""
    return super().to_qiskit(spec)