Engines¶
Engines are the computational backends that perform low-level state operations. Each kind has an abstract interface, so a custom engine can be swapped in.
Two Engine Types:
Stabilizer Engines: Handle Clifford gates efficiently
Tensor Network Engines: Manage non-Clifford effects via MPO
Stabilizer Engine¶
Stabilizers engine backed by stim.
- class mpstab.engines.stabilizers.stim.StimEngine[source]¶
Bases:
StabilizersEngineClifford backpropagation of Pauli observables, powered by stim.
- backpropagate(observable: str, clifford_circuit: Circuit)[source]¶
Evolve
observableback throughclifford_circuit(Heisenberg picture).- Returns:
(pauli_string, sign)forU^dag . O . U, withUthe circuit.
- backpropagate_at(observables: Sequence[str], breakpoints: Sequence[int], clifford_circuit: Circuit) list[source]¶
Backpropagate each observable through its own prefix of
clifford_circuitwith one stim tableau pass.The circuit is simulated once, a segment at a time in breakpoint order, and each observable is conjugated by the inverse tableau of its prefix, so the cost is one pass over the circuit plus one conjugation per observable.
- Raises:
ValueError – on a breakpoint outside
[0, len(clifford_circuit.queue)].
- backpropagate_many(observables, clifford_circuit: Circuit) list[source]¶
backpropagate()every observable through the same circuit.The circuit’s
U^dagtableau is built once and cached, so a whole Hamiltonian costs one stim simulation plus one tableau lookup per term, and repeated calls on an unchanged circuit skip the simulation too.
- instructions(circuit: Circuit) list[source]¶
One stim instruction line per gate of
circuit,Nonefor gates that leave the Pauli frame untouched.stim parses a whole program from text far faster than it appends instructions one call at a time, so circuits are assembled as text.
- Raises:
ValueError – on a non-Clifford rotation angle, or a gate with no stim equivalent. Unsupported gates fail loudly rather than being dropped, which would silently give a wrong Pauli frame.
- mpstab.engines.stabilizers.stim.circuit_instructions(circuit: Circuit) list[source]¶
One stim instruction line per gate of
circuit,Nonefor no-ops.
- mpstab.engines.stabilizers.stim.gate_instruction(gate)[source]¶
The stim instruction line for one Clifford qibo gate, or
Noneif it is a no-op on the Pauli frame.- Raises:
ValueError – on a non-Clifford rotation angle, or a gate with no stim equivalent.
Stim Engine: Clifford backpropagation of Pauli observables with the C++ Stim simulator.
Tensor Network Engine¶
Tensor-network engine backed by quimb.
- mpstab.engines.tensor_networks.quimb.GATE_MAP = {'ccx': 'CCX', 'ccy': 'CCY', 'ccz': 'CCZ', 'cnot': 'CNOT', 'cswap': 'CSWAP', 'cx': 'CX', 'cy': 'CY', 'cz': 'CZ', 'fredkin': 'FREDKIN', 'fsim': 'fsim', 'h': 'H', 'iswap': 'ISWAP', 'measure': 'measure', 'rx': 'RX', 'rxx': 'RXX', 'ry': 'RY', 'ryy': 'RYY', 'rz': 'RZ', 'rzz': 'RZZ', 's': 'S', 'swap': 'SWAP', 't': 'T', 'toffoli': 'TOFFOLI', 'u3': 'U3', 'x': 'X', 'y': 'Y', 'z': 'Z'}¶
qibo gate names mapped to their quimb equivalents.
- class mpstab.engines.tensor_networks.quimb.QuimbEngine(backend: str = 'numpy', svd_cutoff: float | None = None)[source]¶
Bases:
TensorNetworkEngineMPS evolution and MPO expectation values via quimb.
Besides evolving states, it conjugates operators, which
HQSMPO’s head/tail split needs, and its MPS feeds quimb’s DMRG.- apply_pauli_sum(state_circuit: MatrixProductState, paulis, coefficients, max_bond_dimension: int | None) MatrixProductState[source]¶
A new state
sum_t c_t P_t |state>.The terms are stacked into block-diagonal MPOs of
_PAULI_SUM_CHUNKterms each, compressed exactly and summed (a sum of local strings keeps a small bond), and the result is applied to the state and compressed tomax_bond_dimension.
- apply_rotation(state_circuit: MatrixProductState, rotation, max_bond_dimension: int | None)[source]¶
Apply a
rotation_operator()result to the state in place, then compress.A
(generator, angle)tuple only touches the sites between the first and last non-identity letter of its generator, recompressing that window alone; an MPO goes through quimb’sgate_with_mpo, which recompresses the whole chain. Both truncate with the same rule.
- bond_dimension(state_circuit: MatrixProductState) int[source]¶
The largest bond dimension of the MPS.
- build_circuit_mps(n: int, initial_state_circuit: Any, max_bond_dimension: int | None = None)[source]¶
Build the MPS by running
initial_state_circuitthrough quimb.
- circuit_truncation_fidelity(nqubits: int, circuit, max_bond_dimension: int | None) float[source]¶
quimb’s
CircuitMPS.fidelity_estimateafter runningcircuit.
- conjugate_operator(operator: MatrixProductOperator, generator: str, angle: float, max_bond_dimension: int)[source]¶
Heisenberg-conjugate
operatorbyR = exp(-i angle/2 generator), returningR^dag . operator . R.Folds the rotation into the observable so that
<R psi| O |R psi> = <psi| R^dag O R |psi>. The generators are Pauli strings, soR(angle)^dag == R(-angle), and each MPO-MPO product is compressed tomax_bond_dimension.Even at
max_bond_dimension=Nonequimb applies its default SVD cutoff, and the exact operator rank of a scrambled observable grows exponentially, so folding a long tail accrues truncation error. Keeping this exact is only affordable for modest tail lengths; seetail_truncation()to quantify it.
- conjugate_operator_many(operator: MatrixProductOperator, rotations, max_bond_dimension: int | None)[source]¶
Conjugate
operatorby each(generator, angle)rotation in turn, the first one innermost, as repeatedconjugate_operator()calls.On the numpy backend the MPO is unpacked once into canonical site arrays, and each conjugation touches only its generator’s window (
operator_conjugation()), with the same truncation rule as quimb’scompress, so a whole tail costs about as much as evolving a state through it. Other backends go through quimb.
- copy_state(state_circuit: MatrixProductState)[source]¶
An independent copy of the state.
On the numpy backend the copy has its own tensors but shares their arrays: the windowed kernels, like quimb’s own operations, replace a tensor’s array rather than write into it, so neither state can change the other. The cached canonical form is carried over, so the copy needs no re-canonicalization. Other backends get a deep copy.
- expval(state_circuit: MatrixProductState, operator: MatrixProductOperator)[source]¶
Expectation value of
operatoronstate_circuit, normalised.Truncation costs the state its unit norm, so the contraction is divided by it.
A Pauli string from
pauli_mpo()is evaluated directly on the state’s canonical form, over the sites between the string’s support and the orthogonality center only. This may move the center, a pure gauge change that leaves the state itself untouched.Any other operator MPO has upper (output) index
k{i}and lower (input) indexb{i}. The ket must feed the operator’s input, so it is reindexedk -> bwhile the conjugated bra keepsk{i}to meet the output. Reindexing the bra instead would evaluate<psi|O^T|psi>, which differs for any operator with an odd number of Y’s.
- minimize_energy(operator: MatrixProductOperator, initial_state: MatrixProductState, bond_dims: list, cutoff: float, tol: float, max_sweeps: int, verbosity: int) dict[source]¶
Two-site DMRG with quimb’s
DMRG2, on a copy ofinitial_state.
- operator_site_arrays(operator: MatrixProductOperator) list[source]¶
The MPO’s site tensors as numpy arrays ordered
(left, right, k, b),kthe upper (output) andbthe lower (input) index.
- pauli_expvals(state_circuit: MatrixProductState, paulis)[source]¶
Normalised expectation values of many Pauli strings on one state.
The strings are visited in order of their first non-identity site, with the orthogonality center moved to each in turn, so a whole Hamiltonian costs one sweep of the chain plus each term’s own support rather than a full contraction per term.
- Returns:
a real array on the numpy backend, a list of backend scalars otherwise.
- Return type:
One value per string, in the order given
- pauli_rot(state_circuit: MatrixProductState, generator: str, angle: float, max_bond_dimension: int)[source]¶
Apply
exp(-i angle/2 generator)to the state in place, then compress.
- pauli_sum_mpo(terms: dict) MatrixProductOperator[source]¶
The MPO of
sum_P c_P P.- Raises:
ValueError – if
termsis empty.
- pauli_transitions(bra_state: MatrixProductState, ket_state: MatrixProductState, paulis, normalize: bool = True)[source]¶
Transition amplitudes
<bra|P|ket>of many Pauli strings between two states, withnormalizedivided by the norms of both states.- Returns:
A complex array on the numpy backend, a list of backend scalars otherwise.
- rotation_operator(generator: str, angle: float)[source]¶
exp(-i angle/2 generator)in a formapply_rotation()accepts: a(generator, angle)tuple on the numpy backend, applied by the windowed kernel, and the backend MPO otherwise.
- site_arrays(state_circuit: MatrixProductState)[source]¶
The state as the form
_mps_kernelsworks on: a list of(left, phys, right)arrays in mixed canonical form, and the orthogonality center. numpy backend only.The arrays are read-only and shared with the state; the kernels never write into an array, they replace it in the list.
- squared_norm(state_circuit: MatrixProductState)[source]¶
<psi|psi>of the MPS. On the numpy backend it is read off the orthogonality center of the cached canonical form, no full contraction needed; other backends return quimb’s backend scalar, so it stays differentiable.On the numpy backend, when the state has no valid cached canonical form (a fresh state, or one changed outside the engine), it is canonicalized in place first: its tensors are transposed and gauge-transformed, the state itself is unchanged.
- static state_from_arrays(arrays) MatrixProductState[source]¶
An MPS from
(left, phys, right)site arrays, two sites or more.
- property truncation_cutoff: float¶
The relative singular-value cutoff rotations are compressed with.
Quimb Engine: MPS evolution, MPO expectation values and operator conjugation with quimb, on the numpy, jax or torch backend.
Native Engines¶
Pure-Python implementations of the two interfaces, kept as readable examples
of what an engine does rather than for performance. They give the same
expectation values as stim and quimb, but are slower and cover less: the
native tensor-network engine has no operator-side conjugation (so no head/tail
split in HQSMPO) and no DMRG.
Pure-Python stabilizers engine.
- mpstab.engines.stabilizers.native.engine.GATE_TABLEAUS = {'cx': 'CNOT', 'cz': 'CZ', 'gpi2': 'GPI2', 'h': 'H', 'rx': 'RX', 'ry': 'RY', 'rz': 'RZ', 's': 'S', 'sdg': 'Sdg', 'swap': 'SWAP', 'x': 'X', 'y': 'Y', 'z': 'Z'}¶
qibo gate names mapped to the tableau class in
tableausthat implements them.
- class mpstab.engines.stabilizers.native.engine.NativeStabilizersEngine[source]¶
Bases:
StabilizersEngineClifford backpropagation by composing per-gate tableaus.
A pure-Python example of the
StabilizersEngineinterface, written to be read rather than to be fast: useStimEnginefor real workloads.
Native Stabilizers Engine: backpropagates a Pauli string by composing one
tableau per gate, on the XZ-encoded Pauli arithmetic of
mpstab.engines.stabilizers.native.pauli_string.
Pure-Python tensor-network engine.
- class mpstab.engines.tensor_networks.native.engine.NativeTensorNetworkEngine[source]¶
Bases:
TensorNetworkEngineMPS evolution and expectation values on the in-package tensor network.
A pure-Python example of the
TensorNetworkEngineinterface, written to be read rather than to be fast: useQuimbEnginefor real workloads. Supports state-side evolution and expectation values. Operator-side conjugation, and so the whole head/tail split ofHQSMPO, needsQuimbEngine.- build_circuit_mps(n: int, initial_state_circuit: Any, max_bond_dimension: int | None = None)[source]¶
Build a
CircuitMPSin the product state a qibo circuit of one-qubit gates prepares, simulating each qubit on its own.
- expval(state_circuit: CircuitMPS, operator: PauliMPO)[source]¶
Expectation value of
operatoronstate_circuit.
Native Tensor Network Engine: an MPS in Vidal canonical form on a small
in-package tensor-network layer
(mpstab.engines.tensor_networks.native.circuit_mps), evolved by
applying MPOs and re-splitting by SVD.
Selecting Engines¶
Engines are automatically selected based on your circuit type and parameters:
from qibo import Circuit, gates
from mpstab import HSMPO
from mpstab.models.ansatze import HardwareEfficient
clifford_circuit = Circuit(nqubits=10)
# Add only Clifford gates
for q in range(10):
clifford_circuit.add(gates.H(q))
clifford_circuit.add(gates.CNOT(q0=q%10, q1=(q+1)%10))
# Clifford circuit - uses stabilizer engine only
simulator = HSMPO(ansatz=clifford_circuit)
# Constructing a circuit with also magic gates
mixed_circuit = HardwareEfficient(
nqubits=10,
nlayers=3,
)
# Mixed circuit with bond limit - uses both engines
simulator = HSMPO(
ansatz=mixed_circuit,
max_bond_dimension=32 # Enables tensor network engine
)
For detailed guidance, see Working with Engines
Engine Interface¶
All engines implement standardized interfaces for compatibility.
Base Engine Classes:
from mpstab.engines import StabilizersEngine, TensorNetworkEngine
These abstract base classes define the required methods that any engine must implement.
The evolutors never look inside an engine’s states or operators: everything
they need goes through these methods, so a new tensor-network engine only has
to implement them. tests/test_engine_agnostic.py enforces this with an
engine whose states and operators expose nothing.
|
Needed for |
|---|---|
|
Required: building and evolving the MPS, expectation values and truncation fidelities. |
|
Optional, with a generic default an engine may override for speed. |
|
Optional: the head/tail split of |
|
Optional: DMRG ( |
|
Optional: |
An optional method an engine does not implement raises NotImplementedError
only when the feature that needs it is used.
A stabilizers engine is where the Clifford part of the circuit is handled; the evolutors and the noise compiler only ask it for backpropagated Pauli strings.
|
Needed for |
|---|---|
|
Required: dressing observables with the Clifford circuit. |
|
Optional, with a generic default an engine may override to share work across observables. |
|
Dressing each magic gate and noise event with the Clifford gates before
it. The default replays each prefix through |
See Also¶
Working with Engines - Engine selection guide
A quick introduction to mpstab - Practical examples