Skip to content

Qiskit integration

The optional tensorweaver.qiskit module runs Qiskit circuits on the MPS engine. A QuantumCircuit is converted to a mimiq circuit and evolved, so your Qiskit code stays unchanged.

Install the extra:

pip install 'mimiq-tensorweaver[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 little-endian ordering TensorWeaver uses natively. The conversion handles this, so read Qiskit results as Qiskit results.

Sampling

TensorWeaverBackend is a Qiskit BackendV2. Simulator options (bonddim, seed, algorithm, and the rest listed under Choosing a simulator) are fixed when the backend is built. run takes shots and seed, and the circuit-preparation options of TwSimulator.execute: reorderqubits, fuse, fuse_threshold and canonicaldecompose, as in backend.run(qc, shots=4000, reorderqubits=True).

from qiskit import QuantumCircuit
from tensorweaver.qiskit import TensorWeaverBackend

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

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

simulator="direct" runs the circuits on TwDirectSimulator instead; see Choosing a simulator for the options each takes.

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

TensorWeaverEstimator is an EstimatorV2. Every Pauli term is read exactly from the MPS, 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 the other simulator options, and reported as min_fidelity in the result metadata.

from qiskit import QuantumCircuit
from qiskit.quantum_info import SparsePauliOp
from tensorweaver.qiskit import TensorWeaverEstimator

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

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

estimator = TensorWeaverEstimator(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, a noise channel, or qubit loss makes TensorWeaver 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 = TensorWeaverEstimator(trajectories=4000, seed=1)
result = averaged.run([(qc, obs)]).result()[0]
print(result.data.evs, "+/-", result.data.stds)

sampled = TensorWeaverEstimator(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.

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 tensorweaver import TwSimulator
from tensorweaver.qiskit import TensorWeaverEstimator

sim = TwSimulator(bonddim=128, algorithm="vmpoa")
estimator = TensorWeaverEstimator(simulator=sim)

reorderqubits= on the estimator applies qubit reordering to every circuit it runs, as TwSimulator.execute(reorderqubits=...) does; see Qubit ordering.

Choosing a simulator

Both TensorWeaverBackend and TensorWeaverEstimator take simulator=, which picks the TensorWeaver engine behind them:

  • "mpo" (default) is TwSimulator. Gates are fused into matrix product operators (MPOs), and each MPO is applied to the state in one sweep. It favours deep, dense circuits at large bonddim.
  • "direct" is TwDirectSimulator. Each gate is applied to the state as it comes, and qubits that are not neighbours are brought together with swaps. It favours circuits of local gates, or with few gates per qubit between read-outs. It refuses circuits containing BondDim, SchmidtRank or VonNeumannEntropy and noise channels on three or more qubits, and has no GPU path.

Every other keyword goes to the chosen simulator's constructor, and is fixed for the life of the backend or estimator. A keyword the chosen simulator does not take raises TypeError, and an unknown simulator raises ValueError.

from tensorweaver.qiskit import TensorWeaverBackend, TensorWeaverEstimator

# MPO simulator: bond dimension 64, canonical MPO application.
backend = TensorWeaverBackend(bonddim=64, algorithm="cmpo", seed=1)

# Direct simulator: bond dimension 64, the qubit moved is always the target.
backend = TensorWeaverBackend(simulator="direct", bonddim=64, routing="target", seed=1)

# The estimator takes the same choice and the same options.
estimator = TensorWeaverEstimator(simulator="direct", bonddim=128)

mock=True runs the chosen simulator's mock instead, MockTensorWeaver for "mpo" and MockTensorWeaverDirect for "direct". 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.

import os

mock = os.environ.get("TW_MOCK") == "1"
backend = TensorWeaverBackend(simulator="direct", mock=mock, bonddim=64)

On the estimator, seed is its own argument rather than a simulator option, and simulator may also be an existing simulator instance, used as is (see Expectation values); no options and no mock may be passed with one.

Options of simulator="mpo"

Option Default Meaning
bonddim 256 Maximum MPS bond dimension, the memory and accuracy knob. Lowering it truncates earlier and lowers the reported fidelity.
entdim 16 Maximum bond dimension of the MPO that gates are fused into. Larger values batch more gates per sweep. A gate whose operator rank exceeds it raises rather than being applied at reduced accuracy.
sv_cutoff None (1e-7) Singular values below this are discarded when an MPO is applied to the state.
mpo_cutoff None (1e-15) Singular values below this are discarded while gates are fused into an MPO.
algorithm "vmpoa" How each MPO is applied. "dmpo" is a single zip-up pass, the cheapest. "cmpo" is a single pass that truncates against the state's own Schmidt spectrum, and the accurate choice on the GPU. "vmpoa" and "vmpob" run single- and two-site variational sweeps seeded by a zip-up. See Choosing an algorithm.
strict_bonddim None Whether every intermediate bond must stay within bonddim while an MPO is applied. None is strict for "dmpo", "vmpoa" and "vmpob" and relaxed for "cmpo". A strict run with bonddim < entdim raises ValueError, as does "cmpo" with strict_bonddim=True. Relaxed uses more memory and time and is exact whenever the result fits under bonddim.
post_compress True Restore canonical form and compress after every MPO application. Turning it off is faster on states well below bonddim, but can corrupt the state once the bond dimension grows, with the reported fidelity still reading 1.
buffer 0 How many MPOs a background thread fuses ahead while the current one is applied. Results are identical; 2 to 4 is enough.
traversal "sequential" The order gates are fused in: "sequential", "bfs" or "dfs". The state is the same; only how gates batch into MPOs, and so the runtime, changes.
usegpu False Evolve the state on an NVIDIA GPU. Requires algorithm="dmpo" or "cmpo", and linalg unset or "openblas". Faster than the CPU from a bond dimension of about 64 upward, slower below.
linalg None Linear-algebra library: "openblas", "mkl" or "faer". None takes the preferred one this build ships.
seed None Master RNG seed for every run (backend only). None draws fresh entropy per run.
max_num_threads None The most threads a run uses. None leaves it to the process setting.
usemkl None Deprecated, use linalg.

Options of simulator="direct"

Option Default Meaning
bonddim 256 Maximum MPS bond dimension, the memory and accuracy knob.
sv_cutoff None (1e-7) Singular values below this are discarded by every gate and every routing swap.
max_gate_qubits 4 The most qubits a gate may act on in one step. A larger gate is decomposed.
routing "lookahead" Which qubit a two-qubit gate on non-neighbours moves. "lookahead" moves whichever leaves the next gates closer, as long as no swap can truncate. "target" always moves the gate's second qubit next to its first.
linalg None Linear-algebra library: "openblas", "mkl" or "faer". None takes the preferred one this build ships.
seed None Master RNG seed for every run (backend only). None draws fresh entropy per run.
max_num_threads None The most threads a run uses. None leaves it to the process setting.
usemkl None Deprecated, use linalg.

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.