Skip to content

Qiskit integration

The optional tensorkeeper.qiskit module runs Qiskit circuits on TensorKeeper. A QuantumCircuit is converted to a MIMIQ circuit and evolved, so your Qiskit code stays unchanged.

Install the extra:

pip install 'mimiq-tensorkeeper[qiskit]'

Bit ordering

Qiskit's own convention applies to Qiskit objects: counts keys come back with the highest-indexed qubit on the left, the reverse of the MIMIQ ordering TensorKeeper uses natively. The conversion handles this, so read Qiskit results as Qiskit results.

Sampling

TensorKeeperBackend is a Qiskit BackendV2. Simulator options (bonddim, sv_cutoff, disentangle_period and the rest listed under Choosing a simulator) are fixed when the backend is built. run takes shots, seed and memory, and the circuit-preparation options of TkSimulator.execute, such as simplify.

seed is a run option, not a simulator option. TensorKeeperBackend(seed=1) sets its default, so every run of that backend is seeded with 1 and repeats exactly; backend.run(qc, seed=2) overrides it for one call. Left unset, each run draws fresh entropy.

from qiskit import QuantumCircuit
from tensorkeeper.qiskit import TensorKeeperBackend

qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()

backend = TensorKeeperBackend(bonddim=64, seed=1)
counts = backend.run(qc, shots=4000).result().get_counts()

It also works under Qiskit's V2 primitives:

from qiskit.primitives import BackendSamplerV2

sampler = BackendSamplerV2(backend=backend)
result = sampler.run([qc], shots=4000).result()[0]
counts = result.data.meas.get_counts()

Expectation values

TensorKeeperEstimator is an EstimatorV2. Every Pauli term is read exactly from the state, whatever its weight, so there is no shot noise and the reported standard errors are zero. The only error is the MPS truncation itself, set by bonddim and sv_cutoff, and reported as min_fidelity in the result metadata.

The terms are cheap as well as exact. A Pauli term is conjugated through the Clifford frame into another Pauli string and read off the MPS with one inner product, so a term on every qubit costs about as much as a term on one, and the frame's entanglement costs nothing at all (see Concepts). That is what makes large observables on Clifford-heavy circuits, such as stabilizer codes with a few non-Clifford gates, practical.

from qiskit import QuantumCircuit
from qiskit.quantum_info import SparsePauliOp
from tensorkeeper.qiskit import TensorKeeperEstimator

qc = QuantumCircuit(3)
qc.h(0)
qc.cx(0, 1)
qc.t(1)
qc.ry(0.7, 2)

obs = SparsePauliOp.from_list([("ZZI", 1.0), ("IIZ", 0.5), ("XYZ", 0.25)])

estimator = TensorKeeperEstimator(bonddim=64)
result = estimator.run([(qc, obs)]).result()[0]
print(result.data.evs, result.data.stds)

An estimator pub carries state preparation, not readout, so a measurement left at the end of the circuit is dropped rather than collapsing the state the observable is read from.

Circuits that end in an ensemble

That exactness needs the circuit to end in one definite state. A mid-circuit measurement, a reset or a noise channel makes TensorKeeper re-evolve the circuit once per shot, and each trajectory has its own expectation value. The quantity you want, Tr(rho O), is their average, so the estimator needs a budget to estimate it:

Argument What it does
trajectories=N Average N trajectories. Each contributes an exact value, so only the ensemble is sampled. stds is the standard error of the mean.
shots=N Estimate from measurements in rotated Pauli bases, N shots per basis, as hardware and Qiskit's BackendEstimatorV2 do. Terms that commute qubit-wise share a basis, so an observable needing several costs N shots in each.
precision=p Size either budget as ceil(1/p**2), Qiskit's convention.
method=... Force "exact", "trajectories" or "shots" instead of letting "auto" choose from the circuit.
qc = QuantumCircuit(1, 1)
qc.h(0)
qc.measure(0, 0)   # state preparation, not readout: the x follows it
qc.x(0)

obs = SparsePauliOp("Z")   # -1 or +1 per trajectory, 0 over the ensemble

averaged = TensorKeeperEstimator(trajectories=4000, seed=1)
result = averaged.run([(qc, obs)]).result()[0]
print(result.data.evs, "+/-", result.data.stds)

sampled = TensorKeeperEstimator(shots=4000, seed=1)   # the same quantity

Given no budget, a stochastic circuit raises rather than returning one trajectory as though it were exact. method="exact" forces that single-trajectory read anyway, with a warning: it is an unbiased draw, but its spread is the observable's own range, not a small error.

For the same budget, averaging trajectories is never worse than sampling and is usually better, because sampling adds the observable's shot noise on top of the ensemble's, and it runs one basis rather than several. Reach for shots= when you need to reproduce what a shot-based estimator would report, not for accuracy.

Reading the metadata

{'target_precision': 0.0,
 'method': 'trajectories',   # or 'exact', 'shots'
 'exact': False,             # True only with no statistical error at all
 'stochastic': True,         # one evolution per shot was needed
 'trajectories': 4000,       # or 'shots': N
 'min_fidelity': 0.998}      # lowest MPS fidelity behind the pub

min_fidelity is the truncation error, not a statistical one. Averaging more trajectories does not improve it; raising bonddim does. See Accuracy and Tuning for what drives it.

precision and default_precision do not change an exact value: a deterministic circuit has one answer and no shot budget to spend on it. To see plausible shot noise on such a circuit without paying for it, emulate_shot_noise=True adds Gaussian noise of width precision to the exact value, the way Qiskit's StatevectorEstimator does, for the cost of one evolution.

To reuse a configured simulator across both interfaces, pass it in rather than repeating the options:

from tensorkeeper import TkSimulator
from tensorkeeper.qiskit import TensorKeeperEstimator

sim = TkSimulator(bonddim=128)
estimator = TensorKeeperEstimator(simulator=sim)

The estimator reads each term with TkSimulator.expectation, which you can also call yourself on a state from evolve.

Choosing a simulator

Both TensorKeeperBackend and TensorKeeperEstimator take the options of TkSimulator, fixed for the life of the backend or estimator:

Option Default Meaning
bonddim 256 Maximum bond dimension of the residual MPS, the memory and accuracy knob. Lowering it truncates earlier and lowers the reported fidelity.
sv_cutoff None (1e-8) Singular values below this fraction of the largest are discarded.
disentangle_period 1 How often the Clifford disentangler sweeps: every N MPS operations, "auto", or 0 for never. See Accuracy and Tuning.
max_num_threads None The most threads a run uses. None leaves it to the process setting.
linalg None Linear-algebra library: "openblas", "mkl" or "faer". None takes the preferred one this build ships.

An option TkSimulator does not take raises TypeError. On the estimator, seed is its own argument rather than a simulator option, and simulator may be an existing simulator instance, used as is; no options, gpu or mock may be passed with one.

gpu=True runs on TkSimulatorGpu, with the residual MPS on an NVIDIA GPU. It raises at construction when no GPU is usable rather than falling back to the CPU.

mock=True runs on MockTensorKeeper instead. It takes the same options and refuses the same inputs, needs no licence, and simulates nothing: every shot is the all-zero outcome and every expectation value is 0. It is for testing the code around a backend in CI; see Without a licence. It cannot be combined with gpu.

import os
from tensorkeeper.qiskit import TensorKeeperBackend

mock = os.environ.get("TK_MOCK") == "1"
backend = TensorKeeperBackend(mock=mock, bonddim=64)

Gate coverage

Conversion covers the standard Qiskit gate set. Custom gates and gates with unbound parameters raise mimiq_qiskit.converter.UnsupportedGateError: bind the parameters and decompose custom gates before running.