API Reference¶
The public surface is small: one simulator and its GPU variant, one state, and
the methods on them.
Everything else comes from mimiqcircuits. For how to use these rather than
what they are, start with Getting Started.
TkSimulator is a mimiqcircuits.backends.LocalBackend. The interface's abstract
members are name, version, capabilities, build_state, compile and
evolve; execute is inherited from LocalBackend and built on the last three.
compile is pure: no RNG and no sampling, so one compiled circuit serves every
shot and every trajectory of a run.
Bitstring ordering
BitString("01") sets qubit 0 to 0 and qubit 1 to 1. The leftmost
character is qubit 0. This is the MIMIQ convention, and it is the reverse of
Qiskit's.
Bond dimension
TkState.bond_dim and the BondDim instruction report the bond dimension of
the residual MPS, not of the physical state. A maximally entangled stabilizer
state reads back as 1, because its entanglement is in the Clifford frame. See
Concepts.
Simulator¶
tensorkeeper.TkSimulator
¶
Bases: LocalBackend
Clifford-augmented MPS quantum circuit simulator.
The state is held as |psi> = C |phi>: a Clifford frame C tracked as
a stabilizer tableau, and a matrix product state |phi>, the residual,
carrying only the nonstabilizerness entanglement. Clifford gates and Pauli
noise are absorbed by the frame at O(n) and cost no bond dimension, so a
circuit that is mostly Clifford stays cheap however deep and however wide it
is. Non-Clifford gates go to the MPS as dressed gates, and they are what you
pay for.
The cost model. Bond dimension in |phi> grows with the magic in
the circuit, the number and placement of non-Clifford gates, and not with
the circuit's depth or with the entanglement of |psi>. That makes this
the right simulator for Clifford-dominated workloads (Clifford+T, magic
state cultivation, error correction) and the wrong one for circuits whose
difficulty is spread everywhere, where it does an ordinary MPS simulator's
work and pays a little extra to carry the frame.
Two consequences to absorb before reading any number this backend reports:
- :attr:
.TkState.bond_dimand theBondDiminstruction describe|phi>, not|psi>. A maximally entangled stabilizer state reads back as1. It is the number that governs cost; it is not an entanglement measure. - The first few non-Clifford gates on a wide register are usually free.
Optimization-free disentangling applies a rotation as a single-qubit gate
whenever it can find a qubit where
|phi>is still a product state, so bond dimension typically stays at1until roughly the register's worth of magic has accumulated, and only then starts to climb.
Usage. There are two entry points, and they do different things:
- :meth:
executeis the MIMIQ driver, inherited from :class:~mimiqcircuits.backends.LocalBackend. It runs the pass pipeline, decides between sampling and trajectory mode, evolves, samples, and hands back :class:~mimiqcircuits.QCSResults. This is what you want almost always. - :meth:
build_state/ :meth:compile/ :meth:evolveare the three primitivesexecuteis built from. Drive them yourself when you want one evolution and then many non-destructive queries against the resulting :class:.TkState.
Qubit and classical-bit indices are 0-based, as in mimiqcircuits.
Configuration is construction-only: build a new simulator to change a knob
rather than overriding it per call, which keeps the execute keyword
surface free of sentinel-versus-explicit collisions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bonddim
|
int
|
Maximum bond dimension for the residual MPS, and the value
advertised as |
256
|
sv_cutoff
|
Optional[float]
|
Singular values below this fraction of the largest one are
discarded during compression, regardless of |
None
|
disentangle_period
|
int | str
|
How often to run the Clifford disentangler, measured
in MPS-touching operations. The disentangler looks for a two-qubit
Clifford at each cut that lowers the entropy there, applies it to
the MPS and compensates it in the frame. That is an exact re-split
of A positive integer Keeping the bond dimension low makes every later MPS operation
cheaper, since their cost grows as its cube, so the sweeps usually
pay for themselves: on |
1
|
max_num_threads
|
Optional[int]
|
The most threads a run of this simulator uses, for
the linear algebra and for sampling alike. |
None
|
linalg
|
Optional[str]
|
The linear algebra library the residual MPS runs on:
|
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
RuntimeError
|
On the public kernel-free build, where only
:class: |
Examples:
A deep, wide Clifford circuit produces a highly entangled state and
costs nothing:
>>> import mimiqcircuits as mc
>>> from tensorkeeper import TkSimulator
>>> sim = TkSimulator(bonddim=128)
>>> c = mc.Circuit()
>>> for _ in range(50):
... for q in range(40):
... _ = c.push(mc.GateH(), q)
... for q in range(39):
... _ = c.push(mc.GateCX(), q, q + 1)
>>> state, fidelity = sim.evolve(sim.build_state(40), sim.compile(c))
>>> len(c), state.bond_dim
(3950, 1)
>>> type(fidelity).__name__
'ExactFidelity'
The same circuit on a plain MPS simulator would need a bond dimension of
up to ``2**20`` to stay exact.
Driving it through ``execute`` instead, with measurements and shots:
>>> c = mc.Circuit()
>>> _ = c.push(mc.GateH(), 0)
>>> _ = c.push(mc.GateCX(), 0, 1)
>>> _ = c.push(mc.Measure(), 0, 0)
>>> _ = c.push(mc.Measure(), 1, 1)
>>> results = TkSimulator().execute(c, nsamples=100, seed=42)
>>> sorted(bs.to01() for bs in results.histogram())
['00', '11']
>>> sum(results.histogram().values())
100
name
property
¶
The backend's name, as reported in results.simulator.
Returns:
| Type | Description |
|---|---|
str
|
The constant string |
Examples:
>>> from tensorkeeper import TkSimulator
>>> TkSimulator().name
'TensorKeeper'
version
property
¶
The installed package version, as reported in results.version.
Read from the installed distribution metadata rather than hard-coded, so
a bug report's version string always names something installable. This is
the Python package's version; the core it wraps reports its own through
:func:tensorkeeper.library_info.
Returns:
| Type | Description |
|---|---|
str
|
The value of :data: |
str
|
|
str
|
with no installed distribution metadata. |
Examples:
>>> import tensorkeeper
>>> tensorkeeper.TkSimulator().version == tensorkeeper.__version__
True
capabilities()
¶
Capabilities this backend can actually execute.
The MIMIQ driver uses this to decide what to admit, so every token here
is a promise that the corresponding operation runs. See
:data:TARGET_CAPABILITIES for the intended final set and for why the
two are kept as separate literals.
Returns:
| Type | Description |
|---|---|
set[str]
|
A fresh mutable set of capability tokens, all drawn from |
set[str]
|
data: |
set[str]
|
so a caller cannot mutate the module state through it. |
Examples:
>>> from tensorkeeper import TkSimulator
>>> caps = TkSimulator().capabilities()
>>> sorted(caps)[:4]
['amplitude', 'bond_dim', 'classical_bits', 'expectation_1q']
>>> "noise" in caps and "feed_forward" in caps
True
limits()
¶
Declared limits; the bond dimension is the binding one.
The advertised max_bond_dim is the cap on the residual |phi>,
which is why a circuit whose physical state is far more entangled than
this can still run exactly.
Returns:
| Name | Type | Description |
|---|---|---|
A |
Limits
|
class: |
Limits
|
|
Examples:
>>> from tensorkeeper import TkSimulator
>>> TkSimulator(bonddim=64).limits().max_bond_dim
64
topology()
¶
Qubit connectivity: all-to-all.
The MPS is a chain, so a distant pair is reached by a SWAP network
rather than being forbidden. Declaring a
:class:~mimiqcircuits.backends.LinearChain instead would make callers
insert those SWAPs by hand for no gain, since the simulator has to build
one anyway.
Returns:
| Name | Type | Description |
|---|---|---|
An |
Topology
|
class: |
Examples:
>>> from mimiqcircuits.backends import AllToAll
>>> from tensorkeeper import TkSimulator
>>> isinstance(TkSimulator().topology(), AllToAll)
True
can_handle(circuit)
¶
Decline up front what evolve would refuse mid-circuit.
The default check reads the capability set, which is too coarse in two
places. Declaring noise admits any Kraus channel, while a Clifford
frame can only absorb the mixed-unitary (Pauli) ones: amplitude damping is
not a Pauli mixture, so there is nothing to sample into the frame. And a
handful of operations belong to no capability token at all, so nothing
gates them.
Both would otherwise surface as an opaque failure part-way through a long circuit rather than an admission error before any work is done. Anything this accepts is then subject to the inherited capability check.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
circuit
|
Circuit
|
The circuit to admit or decline. Only inspected, never modified, and only the first offending operation is reported. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
An |
AdmissionResult
|
class: |
AdmissionResult
|
class: |
|
AdmissionResult
|
|
Examples:
>>> import mimiqcircuits as mc
>>> from mimiqcircuits.backends import Inadmissible, is_admissible
>>> from tensorkeeper import TkSimulator
>>> sim = TkSimulator()
>>> ok = mc.Circuit()
>>> _ = ok.push(mc.GateH(), 0)
>>> _ = ok.push(mc.Depolarizing1(0.1), 0)
>>> is_admissible(sim.can_handle(ok))
True
Amplitude damping is a Kraus channel but not a Pauli mixture, so it
is declined before any work is done:
>>> bad = mc.Circuit()
>>> _ = bad.push(mc.AmplitudeDamping(0.1), 0)
>>> verdict = sim.can_handle(bad)
>>> isinstance(verdict, Inadmissible)
True
>>> "mixed-unitary" in verdict.reason
True
build_state(nq, nb=0, nz=0, **kwargs)
¶
Build a zero state with nq qubits, nb bits, nz zvars.
The state starts at |00...0> with an identity Clifford frame. All
four tuning knobs are copied in here, which is what makes them
construction-only on the simulator: the state carries the configuration,
so changing it afterwards would have no effect on a state already built.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nq
|
int
|
Number of qubits. A zero-qubit state is legal, and the core is then built with a single unused site. |
required |
nb
|
int
|
Number of classical bits, all starting at 0. |
0
|
nz
|
int
|
Number of complex |
0
|
**kwargs
|
object
|
Ignored. Present because the driver may pass hints that other backends use. |
{}
|
Returns:
| Type | Description |
|---|---|
TkState
|
A fresh :class: |
TkState
|
|
TkState
|
device for :class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> from tensorkeeper import TkSimulator
>>> state = TkSimulator(bonddim=32).build_state(4, 2, 1)
>>> state.num_qubits, state.num_bits, state.num_zvars
(4, 2, 1)
>>> state.bond_dim
1
compile(circuit)
¶
Compile a circuit into a form :meth:evolve can run.
Pure, as the interface requires: no RNG, no sampling, no state, and no
dependence on anything but circuit. All the real work is
per-instruction dispatch that depends on the current Clifford frame,
and the frame does not exist until evolution starts (a dressed gate's
support is a function of everything before it), so the artifact is
mostly a wrapper. It expands containers (GateCall, Block,
BlockCall) into the instructions they hold, so a Clifford inside one
still goes to the frame. What it adds is a table of the parts that
depend on an operation alone (a noise channel's branches, a gate's
matrix), filled on first use. The purity is what lets one compiled artifact, and so one
table, serve every trajectory (see :meth:recompile_per_trajectory).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
circuit
|
Circuit
|
The circuit to compile. Not copied and not mutated. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
A |
CompiledCircuit
|
class: |
CompiledCircuit
|
is the circuit with its containers expanded. |
Examples:
>>> import mimiqcircuits as mc
>>> from tensorkeeper import TkSimulator
>>> c = mc.Circuit()
>>> _ = c.push(mc.GateH(), 0)
>>> compiled = TkSimulator().compile(c)
>>> len(list(compiled.source))
1
evolve(state, compiled, *, rng=None, callback=None, stopped=None)
¶
Evolve state in place under compiled.
The main loop. Each instruction is routed by _apply_instruction to
the classical register, the Clifford frame, or the MPS.
The second return value is the accuracy claim for the run, and its type carries information the number does not:
- :class:
~mimiqcircuits.backends.ExactFidelity: thebonddimcap never bound. Before each operation that can grow a bond, the bonds had room to grow by that operation's full factor. Weight dropped belowsv_cutoffdoes not count against it: that is the requested tolerance. A pure Clifford circuit always reports this. - :class:
~mimiqcircuits.backends.TruncationLowerBound: the cap bound at least once, and the fidelity is at least the reported value, the weight that survived.
TruncationLowerBound(1.0) is deliberately not ExactFidelity.
The claim is about what could have been cut, not about what happened
to be: an operation that reached the cap weakens the claim even if it
discarded nothing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
TkState
|
A :class: |
required |
compiled
|
CompiledCircuit
|
The artifact from :meth: |
required |
rng
|
Optional[Random]
|
A :class: |
None
|
callback
|
Optional[Callable[..., object]]
|
Invoked once per instruction as |
None
|
stopped
|
Optional[object]
|
An object with a |
None
|
Returns:
| Type | Description |
|---|---|
TkState
|
The |
Fidelity
|
passed in, and the accuracy claim described above. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If an instruction is one this backend cannot
execute, such as a Kraus channel that is not a Pauli mixture.
:meth: |
ValueError
|
If an |
IndexError
|
If an instruction addresses a qubit outside |
Examples:
A Clifford circuit is exact, because the MPS is never touched:
>>> import mimiqcircuits as mc
>>> from tensorkeeper import TkSimulator
>>> sim = TkSimulator()
>>> c = mc.Circuit()
>>> _ = c.push(mc.GateH(), 0)
>>> _ = c.push(mc.GateCX(), 0, 1)
>>> state, fidelity = sim.evolve(sim.build_state(2), sim.compile(c))
>>> type(fidelity).__name__
'ExactFidelity'
Counting the instructions through the callback:
>>> seen = []
>>> _ = sim.evolve(sim.build_state(2), sim.compile(c),
... callback=lambda i, total: seen.append((i, total)))
>>> seen
[(1, 2), (2, 2)]
expectation(state, op, *qubits)
¶
Return <psi|op|psi> on state, without changing it.
Exact: nothing is sampled, and the value is that of the state as
evolved, truncation included. op is conjugated through the Clifford
frame rather than applied to the state, so a
:class:~mimiqcircuits.PauliString costs one MPS inner product
however many qubits it spans, and any other operator on m qubits
costs 4**m.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
TkState
|
A :class: |
required |
op
|
A :class: |
required | |
*qubits
|
int
|
The 0-based qubits |
()
|
Returns:
| Type | Description |
|---|---|
complex
|
The complex expectation value. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the number of qubits does not match |
Examples:
>>> import mimiqcircuits as mc
>>> from tensorkeeper import TkSimulator
>>> sim = TkSimulator()
>>> c = mc.Circuit()
>>> _ = c.push(mc.GateH(), 0)
>>> _ = c.push(mc.GateCX(), 0, 1)
>>> state, _ = sim.evolve(sim.build_state(2), sim.compile(c))
>>> sim.expectation(state, mc.PauliString("XX"), 0, 1)
(1+0j)
>>> abs(sim.expectation(state, mc.GateZ(), 0))
0.0
simplify_pass()
¶
The pass execute(simplify=True) installs.
The default pass also resynthesizes gate runs into GateU and
GateCX. A GateU is not recognized as a Clifford even at
Clifford angles, so it would move gates the frame absorbs for free onto
the MPS. This keeps only the passes that never change gate types:
removing identities, cancelling inverse pairs and merging rotations,
which turns T T into S and so moves gates into the frame.
Returns:
| Name | Type | Description |
|---|---|---|
A |
class: |
Examples:
Two ``T`` gates merge into an ``S``, which the frame absorbs:
>>> import mimiqcircuits as mc
>>> from mimiqcircuits.backends.passes import PassContext
>>> from tensorkeeper import TkSimulator
>>> c = mc.Circuit()
>>> _ = c.push(mc.GateT(), 0)
>>> _ = c.push(mc.GateT(), 0)
>>> _ = c.push(mc.GateH(), 0)
>>> simplified, _ = TkSimulator().simplify_pass().apply(PassContext(), c)
>>> [type(i.operation).__name__ for i in simplified]
['GateS', 'GateH']
recompile_per_trajectory(circuit)
¶
Whether each trajectory needs its own compile.
Always False. Mixed-unitary noise is resolved by sampling a Pauli
into the Clifford frame at runtime, inside :meth:evolve, rather than
by baking a chosen branch into the compiled artifact, so one compile
serves every shot and the driver can hoist it out of the trajectory loop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
circuit
|
Circuit
|
The circuit about to be run. Ignored; the answer does not depend on its contents. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
Examples:
>>> import mimiqcircuits as mc
>>> from tensorkeeper import TkSimulator
>>> c = mc.Circuit()
>>> _ = c.push(mc.Depolarizing1(0.1), 0)
>>> TkSimulator().recompile_per_trajectory(c)
False
GPU simulator¶
TkSimulatorGpu is TkSimulator with the residual MPS on an NVIDIA GPU: same
arguments, same capabilities, same results. Check gpu_available first.
tensorkeeper.TkSimulatorGpu
¶
Bases: TkSimulator
Clifford-augmented MPS simulator with the residual MPS on an NVIDIA GPU.
The same simulator as :class:~tensorkeeper.TkSimulator, with the same
arguments, capabilities and results. Every state it builds keeps its
residual MPS |phi> in device memory for the whole run: through
evolution, sampling, and the resets between shots. The Clifford frame stays
on the host, since a frame update is a few word operations per qubit and
never reads the MPS.
When it pays. The device does the MPS work, so it helps when that work is large: a circuit with enough magic to push the bond dimension up. On a Clifford-dominated circuit whose residual stays small, the CPU simulator is as fast or faster, because there is little MPS work to move.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bonddim
|
int
|
As for :class: |
256
|
sv_cutoff
|
Optional[float]
|
As for :class: |
None
|
disentangle_period
|
int | str
|
As for :class: |
1
|
max_num_threads
|
Optional[int]
|
As for :class: |
None
|
linalg
|
Optional[str]
|
The host library under the device engine. The CUDA engine is
built on OpenBLAS, so this must be |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
RuntimeError
|
If :func: |
Examples:
Pick the GPU when there is one:
>>> import tensorkeeper as tk
>>> sim = tk.TkSimulatorGpu() if tk.gpu_available() else tk.TkSimulator()
>>> sim.name in ("TensorKeeper", "TensorKeeperGpu")
True
name
property
¶
The backend's name, as reported in results.simulator.
Returns:
| Type | Description |
|---|---|
str
|
The constant string |
tensorkeeper.gpu_available()
¶
Whether this process could use a GPU.
True means this installation carries the CUDA engine and a device is reachable through it now. Every way of not having one (a CPU-only wheel, no driver, no CUDA libraries, no card) reports False, so this is safe to call anywhere and never raises. The first call probes for a device, which takes a moment when there is a CUDA engine to probe with.
:class:TkSimulatorGpu requires this to be True.
Returns:
| Type | Description |
|---|---|
bool
|
True if a GPU is usable by the core, False otherwise. |
Examples:
>>> import tensorkeeper as tk
>>> isinstance(tk.gpu_available(), bool)
True
State¶
tensorkeeper.TkState
¶
Bases: State
A CAMPS state plus the classical and complex registers.
The quantum register is the Clifford frame and MPS pair held in the Rust
core, reached through :attr:core. The classical bits are a
:class:~mimiqcircuits.BitString and the z-variables a list of
complex numbers, both of which the MIMIQ driver writes into directly and
then copies into results.cstates / results.zstates.
You rarely construct one of these. :meth:.TkSimulator.build_state does it
for you, and execute does that in turn. Building one by hand is worth it
when you want to evolve a circuit and then interrogate the resulting state
repeatedly: :meth:amplitude, :meth:probability and the expectation
values are all non-destructive, so a single evolution can answer many
questions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_qubits
|
int
|
Size of the quantum register. A zero-qubit state is legal but useless, so the core is always built with at least one site. |
required |
num_bits
|
int
|
Size of the classical bit register. Every bit starts at 0. |
0
|
num_zvars
|
int
|
Size of the complex |
0
|
bonddim
|
int
|
Maximum bond dimension for the residual MPS |
256
|
sv_cutoff
|
float
|
Singular values below this fraction of the largest one are discarded during compression. |
1e-08
|
disentangle_period
|
int | str
|
Clifford-disentangler schedule; see
:class: |
1
|
usegpu
|
bool
|
Move the residual MPS to the GPU at construction, and again
after every :meth: |
False
|
engine
|
ModuleType | None
|
The native module to build the core from. Defaults to the one
|
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Attributes:
| Name | Type | Description |
|---|---|---|
core |
CampsCore
|
The Rust CAMPS state, from the engine's module. Everything below delegates to it; reach for it directly only when you need a primitive this class does not wrap. |
Examples:
Build a two-qubit state, evolve a Bell pair onto it, and read the
result back three different ways:
>>> import mimiqcircuits as mc
>>> from tensorkeeper import TkSimulator
>>> sim = TkSimulator()
>>> c = mc.Circuit()
>>> _ = c.push(mc.GateH(), 0)
>>> _ = c.push(mc.GateCX(), 0, 1)
>>> state = sim.build_state(2)
>>> state, _ = sim.evolve(state, sim.compile(c))
>>> round(state.probability(mc.BitString("00")), 6)
0.5
>>> round(state.expectation_paulistring("ZZ", [0, 1]).real, 6)
1.0
>>> state.bond_dim
1
The last line is what the simulator buys: a Bell pair is entangled, but
it is a *stabilizer* state, so all of its entanglement sits in the
Clifford frame and the residual MPS is still a product state at
``chi = 1``.
core
property
¶
The underlying Rust CAMPS state.
The escape hatch for primitives this class does not wrap: the per-bond
profile from core.bond_dims(), the raw Clifford application in
core.apply_clifford(code, qubits), and so on. Nothing on it is part
of the stable Python API; prefer the methods on this class where they
exist.
num_qubits
property
¶
Number of qubits in the quantum register.
num_bits
property
¶
Number of classical bits.
num_zvars
property
¶
Number of complex z-variables.
classical_bits
property
¶
The classical bit register, as a live mutable bitstring.
Measurements write here, the classical-logic operations (Not,
Xor, …) read and write here, and IfStatement
conditions are evaluated against it. The driver copies this object into
results.cstates once per trajectory.
complex_values
property
¶
The complex z-register, as a live mutable list.
ExpectationValue, Amplitude and BondDim write their results
here; Add, Multiply and Pow do arithmetic on it. The driver
copies it into results.zstates.
bond_dim
property
¶
The largest MPS bond dimension currently in use.
This is a property of the residual |phi>, not of the physical
state |psi>. Entanglement carried by the Clifford frame is invisible
to it, so a maximally entangled stabilizer state reads back as 1.
That is the useful number, since it is what the simulator actually stores
and what :meth:.TkSimulator.limits caps, but it is not the state's
Schmidt rank, and it must not be reported as an entanglement measure.
Typically far below the cap: only nonstabilizerness reaches the MPS, so
a Clifford-dominated circuit stays near 1 however deep it runs.
Returns:
| Type | Description |
|---|---|
int
|
The largest bond dimension over all cuts of |
int
|
|
Examples:
A GHZ state on eight qubits is entangled across every cut, and a
plain MPS would need ``chi = 2``. Here the whole circuit is
Clifford, so the residual never leaves ``chi = 1``:
>>> import mimiqcircuits as mc
>>> from tensorkeeper import TkSimulator
>>> sim = TkSimulator()
>>> c = mc.Circuit()
>>> _ = c.push(mc.GateH(), 0)
>>> for q in range(7):
... _ = c.push(mc.GateCX(), q, q + 1)
>>> state, _ = sim.evolve(sim.build_state(8), sim.compile(c))
>>> state.bond_dim
1
is_on_device
property
¶
Whether the residual MPS currently lives in GPU memory.
False for a partly moved state, so this answers "can this be
operated on without transfers", not "is any of it on the device".
Returns:
| Type | Description |
|---|---|
bool
|
|
to_device()
¶
Move the residual MPS onto the GPU for the rest of the run.
The Clifford frame stays on the host. It is a bit-packed tableau updated
in O(n) word operations, so there is nothing for a GPU to do with it,
and a Clifford gate never reads the MPS, so that path costs no transfer
at all.
Worth doing only if the state then stays there for a stretch of circuit:
a round trip costs more than the work it would feed. Move once, evolve,
read at the end. Reads are what to watch, since
:meth:prob_bitstring and sampling walk the register on a copy.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
if this build has no GPU backend, if no device is
reachable, or if the upload fails. Call
:func: |
to_host()
¶
Bring the residual MPS back to host memory.
Succeeds on a state that is already on the host, and in a build with no GPU backend, where there is nothing to bring back.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
if the download fails. |
amplitude(bs)
¶
Amplitude <bs|psi> of a computational-basis state.
The read-out itself is exact, whatever truncation the evolution may have
done. Its cost is exponential in the stabilizer entanglement of the
Clifford frame rather than in the qubit count, which is the price of a
computational-basis amplitude for this representation: the frame is what
turns one basis state of |psi> into a superposition over |phi>.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bs
|
BitString
|
A :class: |
required |
Returns:
| Type | Description |
|---|---|
complex
|
The complex amplitude |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
``T H |0>`` puts a phase of ``exp(i pi/4)`` on the ``|1>`` branch:
>>> import math
>>> import mimiqcircuits as mc
>>> from tensorkeeper import TkSimulator
>>> sim = TkSimulator()
>>> c = mc.Circuit()
>>> _ = c.push(mc.GateH(), 0)
>>> _ = c.push(mc.GateT(), 0)
>>> state, _ = sim.evolve(sim.build_state(1), sim.compile(c))
>>> a0 = state.amplitude(mc.BitString("0"))
>>> a1 = state.amplitude(mc.BitString("1"))
>>> round(abs(a0), 6) == round(abs(a1), 6) == round(1 / math.sqrt(2), 6)
True
>>> round(math.degrees(math.atan2(a1.imag, a1.real)))
45
probability(bs)
¶
Probability |<bs|psi>|^2 of a computational-basis state.
Computed directly rather than by squaring :meth:amplitude, so it is
the right call when the phase is not wanted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bs
|
BitString
|
A :class: |
required |
Returns:
| Type | Description |
|---|---|
float
|
The probability, in |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> import mimiqcircuits as mc
>>> from tensorkeeper import TkSimulator
>>> sim = TkSimulator()
>>> c = mc.Circuit()
>>> _ = c.push(mc.GateH(), 0)
>>> _ = c.push(mc.GateCX(), 0, 1)
>>> state, _ = sim.evolve(sim.build_state(2), sim.compile(c))
>>> [round(state.probability(mc.BitString(b)), 6)
... for b in ("00", "01", "10", "11")]
[0.5, 0.0, 0.0, 0.5]
expectation_paulistring(spec, qubits)
¶
<psi|P|psi> for a Pauli string P over qubits.
The cheap observable. P is conjugated through the Clifford frame,
which maps it to another Pauli string, so the whole thing costs one MPS
inner product no matter how wide P is and no matter how scrambled
the frame. The state is not disturbed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
str
|
Pauli letters, one per entry of |
required |
qubits
|
Sequence[int]
|
The qubit indices |
required |
Returns:
| Type | Description |
|---|---|
complex
|
The expectation value. Real up to rounding for a Hermitian |
complex
|
but returned as a complex number so a phase error is visible rather |
complex
|
than silently discarded. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
IndexError
|
If a qubit index is outside the register. |
Examples:
A Bell pair is a ``+1`` eigenstate of both ``ZZ`` and ``XX``, while
either qubit alone is unpolarized:
>>> import mimiqcircuits as mc
>>> from tensorkeeper import TkSimulator
>>> sim = TkSimulator()
>>> c = mc.Circuit()
>>> _ = c.push(mc.GateH(), 0)
>>> _ = c.push(mc.GateCX(), 0, 1)
>>> state, _ = sim.evolve(sim.build_state(2), sim.compile(c))
>>> round(state.expectation_paulistring("ZZ", [0, 1]).real, 6)
1.0
>>> round(state.expectation_paulistring("XX", [0, 1]).real, 6)
1.0
>>> abs(state.expectation_paulistring("Z", [0])) < 1e-12
True
expectation_operator(matrix, qubits)
¶
<psi|O|psi> for an arbitrary 1- or 2-qubit operator O.
O is decomposed into Paulis and summed, so it never has to be
expanded over its dressed support. The price is 4**len(qubits) inner
products rather than one. Prefer :meth:expectation_paulistring when the
operator already is a Pauli string. The state is not disturbed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
matrix
|
Sequence[Sequence[complex]]
|
The operator, flattened column-major over |
required |
qubits
|
Sequence[int]
|
One or two qubit indices, 0-based. |
required |
Returns:
| Type | Description |
|---|---|
complex
|
The expectation value. Complex for the same reason as in |
complex
|
meth: |
complex
|
error, stays visible. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
IndexError
|
If a qubit index is outside the register. |
Examples:
The projector onto ``|00>`` has expectation ``0.5`` on a Bell pair,
and it is a genuine mixture of Pauli terms rather than a single
string:
>>> import mimiqcircuits as mc
>>> from tensorkeeper import TkSimulator
>>> sim = TkSimulator()
>>> c = mc.Circuit()
>>> _ = c.push(mc.GateH(), 0)
>>> _ = c.push(mc.GateCX(), 0, 1)
>>> state, _ = sim.evolve(sim.build_state(2), sim.compile(c))
>>> p00 = [0j] * 16
>>> p00[0] = 1 + 0j
>>> round(state.expectation_operator(p00, [0, 1]).real, 6)
0.5
A single-qubit ``Z`` agrees with its Pauli-string form, which is the
useful cross-check when a hand-written matrix is suspect:
>>> z = [1 + 0j, 0j, 0j, -1 + 0j]
>>> matrix_form = state.expectation_operator(z, [0])
>>> pauli_form = state.expectation_paulistring("Z", [0])
>>> abs(matrix_form - pauli_form) < 1e-12
True
sample(nsamples, rng=None)
¶
Sample nsamples computational-basis bitstrings.
The state is not disturbed: each draw collapses a throwaway copy, so
repeated calls are independent samples of the same state and every
read-out method still works afterwards. This is what makes execute
cheap on a purely unitary circuit, which evolves once and then samples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nsamples
|
int
|
How many bitstrings to draw. |
required |
rng
|
Optional[Random]
|
A :class: |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
list[BitString]
|
A list of |
|
each |
list[BitString]
|
attr: |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If |
Examples:
A GHZ state only ever yields all-zeros or all-ones, and two
generators with the same seed yield the same draws:
>>> import random
>>> import mimiqcircuits as mc
>>> from tensorkeeper import TkSimulator
>>> sim = TkSimulator()
>>> c = mc.Circuit()
>>> _ = c.push(mc.GateH(), 0)
>>> for q in range(3):
... _ = c.push(mc.GateCX(), q, q + 1)
>>> state, _ = sim.evolve(sim.build_state(4), sim.compile(c))
>>> draws = state.sample(200, random.Random(1234))
>>> sorted({b.to01() for b in draws})
['0000', '1111']
>>> state.sample(5, random.Random(7)) == state.sample(5, random.Random(7))
True
reset()
¶
Reset every register to its zero value, reusing the allocation.
This is what the driver calls between shots. The quantum register is rebuilt in the core rather than reset qubit by qubit: the latter leaves the Clifford frame in place and the accumulated fidelity untouched, which across shots would charge later shots for an earlier shot's truncation.
The configuration and the RNG stream survive, so consecutive shots stay distinct.
Examples:
>>> import mimiqcircuits as mc
>>> from tensorkeeper import TkSimulator
>>> sim = TkSimulator()
>>> c = mc.Circuit()
>>> _ = c.push(mc.GateH(), 0)
>>> _ = c.push(mc.GateCX(), 0, 1)
>>> _ = c.push(mc.GateT(), 1)
>>> state, _ = sim.evolve(sim.build_state(2), sim.compile(c))
>>> state.reset()
>>> round(state.probability(mc.BitString("00")), 6)
1.0
Capabilities¶
tensorkeeper.TARGET_CAPABILITIES = frozenset({'amplitude', 'sampling', 'classical_bits', 'zvars', 'midcircuit_measure', 'midcircuit_reset', 'reset_after_measure', 'feed_forward', 'noise', 'bond_dim', 'expectation_1q', 'expectation_2q', 'expectation_paulistring', 'expectation_state'})
module-attribute
¶
The capability set TensorKeeper is being built towards.
A MIMIQ capability is a promise: declaring one commits the backend to executing
every operation that belongs to it. This literal records the intended final set
so it can be read as a roadmap, and so a conformance test can check the whole set
against :data:~mimiqcircuits.backends.CAPABILITY_VOCABULARY rather than only
the part that works today.
Every entry is also implemented today, so what :meth:TkSimulator.capabilities
returns is equal to this, but the two stay separate literals on purpose. The
comment above the assignment says why an over-declaration is the dangerous
direction.
Every capability below is declared and executes. Anything absent is refused, by
can_handle where it can be detected before the run starts.
| Capability | Instruction it enables |
|---|---|
amplitude |
Amplitude |
sampling |
sampling from the final state |
classical_bits |
Not, And, Or, Xor, SetBit0, SetBit1, ReadoutErr |
zvars |
Add, Multiply, Pow |
midcircuit_measure |
Measure, MeasureX, MeasureY, MeasureXX, MeasureYY, MeasureZZ, MeasurePauli |
midcircuit_reset |
Reset, ResetX, ResetY, PrepareStateT |
reset_after_measure |
MeasureReset, MeasureResetX, MeasureResetY |
feed_forward |
IfStatement |
noise |
mixed-unitary (Pauli) Kraus channels only |
bond_dim |
BondDim |
expectation_1q |
ExpectationValue of a 1-qubit operator |
expectation_2q |
ExpectationValue of a 2-qubit operator |
expectation_paulistring |
ExpectationValue of a PauliString |
Not supported, and declined by can_handle: SchmidtRank, VonNeumannEntropy, WhileStatement, and any non-mixed-unitary
Kraus channel.
Fidelity¶
evolve returns (state, fidelity), where the fidelity is one of
mimiqcircuits.backends' two types:
| Type | Meaning |
|---|---|
ExactFidelity() |
the bonddim cap never bound; weight below sv_cutoff is the requested tolerance |
TruncationLowerBound(v) |
the cap bound at least once; the fidelity is at least v |
Once the cap has bound, the claim is TruncationLowerBound and never
ExactFidelity, and TruncationLowerBound(1.0) is deliberately not
ExactFidelity(). See
Accuracy and Tuning.
Mock backend¶
MockTensorKeeper (also MockTkSimulator) takes TkSimulator's arguments and
runs nothing. See Without a licence.
tensorkeeper.MockTensorKeeper = MockTkSimulator
module-attribute
¶
tensorkeeper.has_kernels()
¶
Whether the installed build carries the compute kernels.
False only in the wheel published on public PyPI, which is compiled
without them: gate application, measurement, sampling, noise and
expectation values are not in that binary in any form.
:class:~tensorkeeper.MockTensorKeeper is the backend it ships;
:class:~tensorkeeper.TkSimulator refuses to construct there.
Every engine in a wheel is built with the same features, so the default engine answers for all of them, once.
Returns:
| Type | Description |
|---|---|
bool
|
|
bool
|
kernel-free one. |
Examples:
>>> import tensorkeeper as tk
>>> isinstance(tk.has_kernels(), bool)
True
Engines and build information¶
tensorkeeper.available_engines()
¶
The engines this installation carries.
A name here means the module is present, not that it will load: the MKL engine can be present and still fail on a machine with no MKL runtime, and the CUDA engine on one with no GPU.
Returns:
| Type | Description |
|---|---|
list[str]
|
Engine names, from |
list[str]
|
in that order. |
Examples:
>>> import tensorkeeper as tk
>>> set(tk.available_engines()) <= {"openblas", "mkl", "faer", "cuda"}
True
tensorkeeper.library_info(linalg=None)
¶
Name, version and copyright of the native core, and of its MPS backend.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
linalg
|
str | None
|
The engine to ask, as for :class: |
None
|
Returns:
| Type | Description |
|---|---|
str
|
A multi-line banner, for logs and bug reports. |
Examples:
>>> import tensorkeeper as tk
>>> tk.library_info().startswith("TensorKeeper core")
True
tensorkeeper.compile_info(linalg=None)
¶
How the native engine was built, as aligned text.
Same content as :func:compile_info_json, one key value per line
with the keys padded to a common width.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
linalg
|
str | None
|
The engine to ask, as for :func: |
None
|
Returns:
| Type | Description |
|---|---|
str
|
The rendered text. |
Examples:
>>> import tensorkeeper as tk
>>> "tensorkeeper_rs_version" in tk.compile_info()
True
tensorkeeper.compile_info_json(linalg=None)
¶
How the native engine was built, as a JSON string.
Records the tensorkeeper-rs version and the MPS backend's build: crate
version, Rust toolchain, target triple, profile, enabled features (which
name the linear algebra library and whether the licence is compiled in),
build time and git revision. Quote it verbatim when reporting a problem.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
linalg
|
str | None
|
The engine to ask, as for :class: |
None
|
Returns:
| Type | Description |
|---|---|
str
|
A JSON object, as a string. |
tensorkeeper.thread_info(linalg=None)
¶
How each thread pool resolved, and what decided it.
The engine runs two pools. core is the linear algebra: gate
application, compression, decompositions. sampler draws shots from the
evolved state. Each entry carries source, what decided the count, and
threads, the count itself or None where the library sized itself.
core also carries effective, the count the linear algebra actually
runs on.
Each pool takes, in order, its own MIMIQ_CORE_NUM_THREADS or
MIMIQ_SAMPLER_NUM_THREADS, then MIMIQ_NUM_THREADS, then the native
variable of the library underneath, then the library's own default.
source is "limit" while a simulator's max_num_threads holds the
count below that. Reach for this when a run does not use the CPUs you
expected; see the Threads page.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
linalg
|
str | None
|
The engine to ask, as for :func: |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
``{"core": {"source", "threads", "effective"}, "sampler": {"source", |
dict
|
"threads"}}``. |
Examples:
>>> import tensorkeeper as tk
>>> sorted(tk.thread_info())
['core', 'sampler']
tensorkeeper.thread_info_json(linalg=None)
¶
How each thread pool resolved, as a JSON string.
Same content as :func:thread_info, unparsed, for logs and bug reports.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
linalg
|
str | None
|
The engine to ask, as for :class: |
None
|
Returns:
| Type | Description |
|---|---|
str
|
A JSON object, as a string. |
Qiskit¶
Needs the qiskit extra; see Qiskit integration.
tensorkeeper.qiskit.TensorKeeperBackend(*, gpu=False, mock=False, name='tensorkeeper', num_qubits=64, seed=None, **tk_options)
¶
Build a Qiskit BackendV2 backed by a TensorKeeper simulator.
The returned backend converts each QuantumCircuit to a MIMIQ circuit
and runs it on :class:~tensorkeeper.TkSimulator. Wrap it in Qiskit's
BackendSamplerV2 for sampling, or use
:class:~tensorkeeper.qiskit.TensorKeeperEstimator for expectation values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gpu
|
bool
|
Run on :class: |
False
|
mock
|
bool
|
Run on :class: |
False
|
name
|
str
|
Backend name reported to Qiskit. |
'tensorkeeper'
|
num_qubits
|
int
|
Qubit count advertised on the Qiskit |
64
|
seed
|
int | None
|
Default for the |
None
|
**tk_options
|
Options of the simulator, fixed at construction:
|
{}
|
Returns:
| Type | Description |
|---|---|
'MimiqBackend'
|
A configured |
Raises:
| Type | Description |
|---|---|
ValueError
|
If both |
Example::
from qiskit.primitives import BackendSamplerV2
from tensorkeeper.qiskit import TensorKeeperBackend
backend = TensorKeeperBackend(bonddim=64, seed=1)
counts = backend.run(qc, shots=1000).result().get_counts()
sampler = BackendSamplerV2(backend=backend)
# Same options, no licence, no simulation: for CI.
ci = TensorKeeperBackend(mock=True, bonddim=64)
tensorkeeper.qiskit.TensorKeeperEstimator
¶
Bases: BaseEstimatorV2
Qiskit EstimatorV2 backed by the TensorKeeper CAMPS simulator.
On a circuit that ends in a definite state, results are exact up to the
MPS truncation set by tk_options: no term is sampled, whatever its
weight, so the reported standard errors are zero and the only error left
is the truncation, reported as min_fidelity in the result metadata.
A circuit carrying a mid-circuit measurement, a reset or a noise channel
ends in an ensemble, and its expectation value is the average over the
trajectories TensorKeeper evolves, one per shot. That average is the
unbiased estimate of :math:\mathrm{Tr}(\rho O), so it is what this
reports, with the sample standard error in stds. Reading one
trajectory would be unbiased too but as noisy as the observable's own
range, so a stochastic circuit with no budget raises rather than
returning it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
simulator
|
An existing TensorKeeper simulator to use as is, in which
case |
None
|
|
gpu
|
bool
|
Evaluate on :class: |
False
|
mock
|
bool
|
Evaluate on :class: |
False
|
method
|
str
|
|
'auto'
|
trajectories
|
int | None
|
Trajectories to average for a stochastic circuit.
|
None
|
shots
|
int | None
|
Shots per measurement basis, estimating from measurements in
rotated Pauli bases the way hardware and Qiskit's
|
None
|
emulate_shot_noise
|
bool
|
Add Gaussian noise of width |
False
|
default_precision
|
float
|
Precision used when |
0.0
|
seed
|
int | None
|
Seed forwarded to every run, and to the |
None
|
**tk_options
|
Options of the simulator, fixed at construction:
|
{}
|
Result metadata reports method, whether the value is exact,
whether the run was stochastic, the trajectories or shots
spent, the target_precision, and min_fidelity: the lowest MPS
fidelity behind the pub. That last one is the truncation error, which
averaging more trajectories does not reduce; raise bonddim for that.
default_precision
property
¶
Precision used when run is called without an explicit one.
run(pubs, *, precision=None)
¶
Estimate every pub and return the job carrying the results.
precision overrides :attr:default_precision for this call. It is
recorded in the result metadata as target_precision, and where a
budget is needed and none was given explicitly, a positive value sizes
it as ceil(1/precision**2).
Bundled files¶
tensorkeeper.examples_dir()
¶
Path to the example scripts bundled with the package.
The examples are a curriculum, meant to be read in order: each one builds on the one before. They ship inside the wheel, so this is how to find them from an installed package rather than a source checkout.
Returns:
| Name | Type | Description |
|---|---|---|
The |
Path
|
class: |
Path
|
folders ( |
Examples:
>>> import tensorkeeper as tk
>>> d = tk.examples_dir()
>>> d.name
'examples'
>>> sorted(p.name for p in d.iterdir() if p.is_dir())[:2]
['00_mock_backend', '01_bell_pair']
Each folder holds one runnable script:
>>> (d / "01_bell_pair" / "main.py").is_file()
True
tensorkeeper.docs_dir()
¶
Path to the HTML documentation bundled with the package.
The published wheel ships the documentation site, so it can be read
offline. Open index.html in a browser, or serve the directory with
python -m http.server -d <docs_dir()> for the search box to work.
Returns:
| Name | Type | Description |
|---|---|---|
The |
Path
|
class: |
Path
|
development install ( |
|
Path
|
documentation. |