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 ¶
A device or simulator that can run a :class:CircuitSpec.
Source code in src/qmlkit/core/backends/base.py
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
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
probabilities ¶
probabilities(spec: CircuitSpec) -> NDArray[Any]
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
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
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
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
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
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
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
is_available ¶
True if this backend's SDK can be imported in the current interpreter.
Source code in src/qmlkit/core/backends/registry.py
list_backends ¶
available_backends ¶
Only the backends whose SDK is actually importable right now.
backend_report ¶
A human-readable summary of which backends this interpreter can run.
Source code in src/qmlkit/core/backends/registry.py
get_backend ¶
Resolve a backend name, instance, or None (the default) to an instance.
Source code in src/qmlkit/core/backends/registry.py
require_statevector ¶
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
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
set_default_backend ¶
Set the process-wide default backend and return it.
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 ¶
Bases: Backend
Exact statevector simulation in NumPy.
Source code in src/qmlkit/core/backends/numpy_backend.py
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
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
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
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 ¶
Bases: Backend
Runs qmlkit circuits on Qiskit's reference statevector simulator.
Source code in src/qmlkit/core/backends/qiskit_backend.py
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
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 ¶
Bases: Backend
Runs qmlkit circuits on cirq.Simulator.
Source code in src/qmlkit/core/backends/cirq_backend.py
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
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 ¶
Bases: Backend
Runs qmlkit circuits on OpenQARP's QarpSimulator.
Source code in src/qmlkit/core/backends/openqarp_backend.py
to_openqarp ¶
to_openqarp(spec: CircuitSpec) -> Block
Translate a bound :class:CircuitSpec into a qarp block.
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
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
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.
Xon qubit 0 of a two-qubit register yields{'10': shots}— qubit 0 is the most significant bit. No remapping needed, unlike Qiskit. result.statesis an exact complex128 statevector, so SpinQit supports an exact mode; it is not sampling-only.result.probabilitiesis a dict keyed by bitstring, not an array.ControlledGate(Rz)reproduces qmlkit'scrzexactly, andP,SdandTdmatchphase,sdgandtdg.- Shots are configured with
config.configure_shots(n). There is nowith_shots;Circuit.measuretakes(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 ¶
Bases: Backend
Runs qmlkit circuits on SpinQit's simulator.
Source code in src/qmlkit/core/backends/spinqit_backend.py
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
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
verify_conventions ¶
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
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 ¶
Bases: Backend
Statevector simulation in torch — differentiable end to end.
Source code in src/qmlkit/core/backends/torch_backend.py
expectation_tensor ¶
expectation_tensor(
spec: CircuitSpec,
theta: Any,
obs: Observable | None = None,
) -> Any
The differentiable path — returns a torch scalar, not a float.
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
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 ¶
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
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
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
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
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 ¶
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
density_matrix ¶
density_matrix(spec: CircuitSpec) -> NDArray[Any]
Final state as a (2**n, 2**n) density matrix, qubit 0 most significant.
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
probabilities ¶
probabilities(spec: CircuitSpec) -> NDArray[Any]
Outcome probabilities: the real diagonal of the density matrix.
Source code in src/qmlkit/core/backends/noisy.py
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
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 ¶
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
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.
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 ¶
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
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.