Evolutors

Evolutors are the high-level managers of a simulation. They partition a circuit into a Clifford part and the magic gates that resist it, then drive the stabilizer and tensor-network engines through the result.

HSMPO: Hybrid Stabilizer MPO

The Clifford part is absorbed into the observable and the magic gates are applied to an MPS as dressed Pauli rotations.

The hybrid stabilizer-MPO surrogate of a quantum circuit.

class mpstab.evolutors.hsmpo.HSMPO(ansatz: Ansatz | Circuit, max_bond_dimension: int = None, initial_state: Circuit = None, progress: bool = True, stab_engine: StabilizersEngine = None, tn_engine: TensorNetworkEngine = None)[source]

Bases: object

Hybrid stabilizer-MPO surrogate of a quantum circuit.

The circuit is split into a Clifford part, handled by a stabilizers engine, and the magic gates it cannot absorb, applied to an MPS as dressed Pauli rotations by a tensor-network engine. Both engines are pluggable, at construction or later through set_engines().

Parameters:
  • ansatz – the circuit to surrogate, as an Ansatz or a plain qibo Circuit.

  • max_bond_dimension – MPS truncation cap, or None for no cap.

  • initial_state – single-qubit-gates-only circuit preparing the initial state. Defaults to |0...0>.

  • progress – show a progress bar while the MPS is evolved through the dressed rotations. It only appears once the evolution has taken longer than about a second, so quick builds stay silent.

  • stab_engine – stabilizers engine, StimEngine if None.

  • tn_engine – tensor-network engine, QuimbEngine if None.

ansatz: Ansatz | Circuit
expectation(observable: str | list | dict | SymbolicHamiltonian, return_fidelity: bool = False)[source]

Expectation value of observable on the full circuit, with no magic-gate replacement.

Parameters:
  • observable – a Pauli string or any other format pauli_terms() accepts.

  • return_fidelity – also return the MPS’s squared norm, which truncation pushes below 1.

expectation_from_partition(observable: str | list | dict | SymbolicHamiltonian, replacement_probability: float, replacement_method: str = 'closest', return_partitions: bool = False, light_cone: bool = True)[source]

Expectation value on a lower-magic circuit sampled from the ansatz.

Parameters:
  • observable – a Pauli string or any other format pauli_terms() accepts.

  • replacement_probability – chance of replacing each magic gate with a Clifford one.

  • replacement_method – "closest" or "random" Clifford angle.

  • return_partitions – also return the magic gates, the Clifford-only circuit, the sampled full circuit and the evolved MPS.

  • light_cone – skip the dressed rotations that cannot affect the observable (pauli_light_cone()). This is exact, and with a bond-dimension cap it also spares those rotations’ truncation error.

Returns:

(expval, partitions), with partitions None unless return_partitions.

get_parameters() → ndarray[source]

The circuit’s current parameters.

gradient(observable: str | list | dict | SymbolicHamiltonian, parameters: List[int] | None = None, light_cone: bool = True, method: str = 'adjoint', costate_bond: int | None = None, groups: int = 1, n_workers: int | None = None, return_value: bool = False)[source]

Gradient of expectation() with respect to the circuit parameters, analytically, instead of the two shifted circuits per parameter of the parameter-shift rule: its cost does not grow with the number of parameters. See analytic_gradient(), which also reports the rotations applied and the truncation fidelities.

Parameters:
  • observable – a Pauli string or any other format pauli_terms() accepts.

  • parameters – indices into get_parameters() to differentiate, all of them by default.

  • light_cone – drop the rotations that cannot affect the observable first, which is exact.

  • method – "adjoint" (default), one forward pass and one backward pass of a costate of twice the bond dimension; or "flips", one shifted tail per parameter, with no costate to truncate.

  • costate_bond – bond cap of the adjoint costate, twice max_bond_dimension by default; max_bond_dimension itself is about twice as fast, for twice the error.

  • groups – differentiate the observable’s terms in this many blocks of neighbouring terms, each on its own, narrower light cone. Faster and more accurate once the union of the cones saturates max_bond_dimension; one block (default) uses the union.

  • n_workers – processes the blocks run on in parallel, min(groups, os.cpu_count()) by default. The pool starts on the first call (about a second per process) and is reused.

  • return_value – also return the expectation value, which the gradient’s forward pass computes anyway: what a training step needs. It is exact like expectation(), but evaluated on the light-cone chain at the parameters of the last partition (set_parameters()), not on the cached MPS.

Returns:

One derivative per requested parameter, or (value, gradient) with return_value.

Raises:

ValueError – if a requested parameter’s gate sits at a Clifford angle, so that it was absorbed into the tableau and has no rotation to differentiate.

initial_mps()[source]

A fresh MPS in the product state initial_state prepares, capped at max_bond_dimension. It belongs to the caller: evolving it leaves this instance untouched.

Raises:

ValueError – if initial_state entangles any pair of qubits.

initial_state: Circuit = None
max_bond_dimension: int = None
minimize_expectation(observables: str | list | dict | SymbolicHamiltonian, method: str = 'dmrg', bond_dims: int | list = None, cutoff: float = 1e-09, tol: float = 1e-06, max_sweeps: int = 10, verbosity: int = 1)[source]

Minimize an observable over MPS tensors with DMRG, starting from the cached MPS.

Parameters:
  • observables – the Hamiltonian to minimize, in any format pauli_terms() accepts.

  • method – only "dmrg" is implemented.

  • bond_dims – max bond dimension per sweep, or one value for all.

  • cutoff – SVD truncation cutoff.

  • tol – energy convergence tolerance.

  • max_sweeps – maximum number of sweeps.

  • verbosity – DMRG verbosity, 0 to 2.

Returns:

A dict with ground_state, energy, converged, num_sweeps and energy_history.

Raises:

NotImplementedError – with a tensor-network engine that does not implement minimize_energy().

property n_clifford_gates: int

Number of Clifford gates in the precomputed Clifford-only Qibo Circuit.

property n_gates: int

Total number of (non-measurement) gates in the original AnsatzCircuit.

property n_magic_gates: int

Number of non-Clifford (“magic”) gates in the original AnsatzCircuit as split up by partitionate_circuit.

noisy_expectation(observable: str | list | dict | SymbolicHamiltonian, noise, n_samples: int = 1000, seed: int | None = None, n_workers: int = 1)[source]

Expectation value of observable on the circuit with noise.

Every set of Pauli faults only flips the signs of some dressed-rotation angles, so the noisy value is an average of noiseless HSMPO values: patterns with zero and one fault are summed exactly, those with two or more are sampled. Coherent errors join the rotation chain like magic gates. A general channel, such as amplitude damping, adds transition amplitudes between two sign patterns, one for the ket and one for the bra. Only the rotations and faults in the light cone are kept, which is exact. Readout errors are folded into the observable’s terms.

Parameters:
  • observable – a Pauli string or any other format pauli_terms() accepts.

  • noise – a NoiseModel.

  • n_samples – fault configurations sampled for two or more faults. With 0 that stratum is dropped, biasing the mean by at most stratum_weights[2] times the sum of the absolute coefficients.

  • seed – seed of the sampler.

  • n_workers – processes evaluating the fault patterns in parallel. The result does not depend on it; each extra process costs about a second to start, so use it for large runs.

Returns:

NoisyExpectation, with the value in mean and its standard error in stderr.

property nparams
property nqubits
progress: bool = True
classmethod rotations_only(ansatz: Ansatz | Circuit, stab_engine: StabilizersEngine = None, tn_engine: TensorNetworkEngine = None)[source]

Build an instance without evolving the MPS, for the dressed-rotation and resynthesis paths that never need it.

Sets up only the ansatz, initial state, engines, magic_gates and clifford_circuit, so construction stays cheap and never touches the (generally exponentially large) exact state. Anything needing original_circuit_mps, expectation() included, raises AttributeError; call set_engines() to upgrade to a full instance.

Parameters:
  • ansatz – the circuit to surrogate.

  • stab_engine – stabilizers engine, StimEngine if None.

  • tn_engine – tensor-network engine, QuimbEngine if None.

set_engines(stab_engine: StabilizersEngine | None = None, tn_engine: TensorNetworkEngine | None = None)[source]

Install the stabilizers and tensor-network engines, then rebuild the cached MPS with them.

Parameters:
  • stab_engine – stabilizers engine, StimEngine if None.

  • tn_engine – tensor-network engine, QuimbEngine if None.

set_parameters(parameters: ndarray)[source]

Set the circuit’s parameters and re-partition the circuit. The cached MPS is rebuilt on its next use, so a training loop that only calls gradient() never pays for it.

stab_engine: StabilizersEngine = None
tn_engine: TensorNetworkEngine = None
truncation_fidelity(replacement_probability: float = 0.0, replacement_method: str = 'closest') → float[source]

Truncation fidelity of the hybrid MPS, \(|\langle\Psi_t|\Psi_t\rangle|^2\), which equals the fidelity against the untruncated state because \(\Psi\) is normalised.

property truncation_fidelity_pure_tn: float

Truncation fidelity of running the whole circuit as a plain MPS, with no stabilizer help: the baseline the hybrid representation improves on.

Usage Example:

from mpstab import HSMPO
from qibo import Circuit, gates

# Create a circuit
circuit = Circuit(5)
circuit.add(gates.H(0))
circuit.add(gates.CNOT(0, 1))

# Simulate with HSMPO
simulator = HSMPO(ansatz=circuit, max_bond_dimension=32)
result, fidelity = simulator.expectation("Z" * 5, return_fidelity=True)
print(f"Expectation value: {result}")
print(f"Fidelity: {fidelity}")

HQSMPO: Head/Tail Split

Splits the dressed-rotation chain in two: a head resynthesized into a circuit a device can run, and a tail folded into the observable. See Hardware Resynthesis with rustiq.

The head/tail split of an HSMPO’s dressed rotations, measured with finite shots.

The dressed-rotation chain is cut at cut_index. The head is resynthesised into a circuit a device can run; the tail is folded into the observable, leaving an MPO. HQSMPO.expectation_at_cut() then measures the head against that observable with a shot budget, by one of the measurement methods of mpstab.qpu.measurement, passed as an object or by name:

  • PauliSampling ("pauli") samples Pauli strings from the tail MPO and groups them into qubit-wise-commuting measurement settings.

  • ClassicalShadows ("shadows") measures random single-qubit Pauli bases and contracts each snapshot against the tail MPO directly.

The head is resynthesised by one of the synthesisers of mpstab.qpu.synthesis, set as head_synthesis.

Resynthesising the head leaves a Clifford residual, so a device prepares U(residual) U(head)|psi_0> rather than the exact head state the tail coefficients were derived against. The "pauli" route corrects for this by conjugating every sampled string through the residual. The "shadows" route takes a tail_handling option:

  • "append_to_head_circuit" (default) runs the residual as extra gates after the head: exact, with the shadow variance of the unfolded tail;

  • "fold" conjugates the observable and every tail generator through the residual before folding the tail, so the device runs the head alone. A Pauli conjugated by a Clifford is a Pauli, so the tail stays a Pauli-rotation fold with the same MPO structure, and the result is exactly R^dag O' R. It saves the residual’s two-qubit gates, but the residual spreads Pauli weight, so the shadow variance sum_P c_P^2 3^w_P of the folded MPO can grow by orders of magnitude: whether it pays off depends on the device’s two-qubit error.

HQSMPO.expectation_at_cut() chains three stages that can also be run separately, e.g. to execute the circuits on a real device and post-process the results later: HQSMPO.plan() builds the circuits and can save them as OpenQASM, a device backend runs them, and the method’s estimate (or estimate()) recombines the frequencies using the plan.

expectation_at_cut(method="simulation") is the classical MPO-MPS contraction of the same split, with the head as a truncated MPS. It is a reference for validating the hardware methods, not a measurement route: this class is meant for hardware, and the hardware methods are the recommended way to use it.

class mpstab.evolutors.hqsmpo.ExpectationResult(value: float, stderr: float, truncation_l1: object, truncation_l2: float, n_settings: int, n_shots: int, retained_weight: float | None = None, state_fidelity: float | None = None, bond_truncation_l2: float | None = None, antihermitian_l2: float | None = None)[source]

Bases: object

A measured expectation value, its shot noise and its truncation budget.

Variables:
  • value (float) – the (real) expectation value.

  • stderr (float) – standard error from shot noise alone.

  • truncation_l1 (object) – heuristic discarded-Pauli-mass estimate (see truncation_error_estimate() – an extrapolation, not a rigorous bound); None for the "shadows" route, whose bond truncation has no L1/L2 split.

  • truncation_l2 (float) – typical-case truncation estimate – Pauli-set truncation for "pauli", MPO bond truncation for "shadows".

  • n_settings (int) – number of distinct circuits the shots came from.

  • n_shots (int) – total shots used.

  • retained_weight (float | None) – "pauli" only, None otherwise – see retained_weight.

  • state_fidelity (float | None) – "simulation" only, None otherwise: the squared norm of the head MPS, which its truncation pushes below 1. The hardware methods run the head on the device, so they have no head truncation to report.

  • bond_truncation_l2 (float | None) – "pauli" only, None otherwise (there truncation_l2 already is the fold truncation): the bias estimate of truncating the tail fold (bond cap or SVD cutoff) – see bond_truncation_l2. Part of total_error.

  • antihermitian_l2 (float | None) – "pauli" only, None otherwise: the size of the anti-Hermitian part the bond truncation left in the sampled coefficients, which was projected out – see antihermitian_l2. A diagnostic, not part of total_error.

antihermitian_l2: float | None = None
bond_truncation_l2: float | None = None
n_settings: int
n_shots: int
retained_weight: float | None = None
state_fidelity: float | None = None
stderr: float
property total_error: float

A practical accuracy bound, not a standard error itself: sqrt(stderr**2 + truncation_l2**2 + bond_truncation_l2**2) (the last term for "pauli" only, where truncation_l2 is the Pauli-set truncation and the bond truncation is reported apart), combining contributions of different nature in quadrature. stderr is a statistical quantity (shot noise, shrinks with more shots); truncation_l2 is a systematic-bias estimate (bond-dimension or Pauli-coverage truncation, independent of shot count – see truncation_l1 and retained_weight to tell which one is dominating). Combining them in quadrature is a convenient, common convention, not a rigorous derivation of a single confidence interval – but it is still the number to report in a results table, since stderr alone omits the truncation bias entirely. For "simulation" it covers the tail truncation only; the head truncation shows in state_fidelity.

truncation_l1: object
truncation_l2: float
value: float
class mpstab.evolutors.hqsmpo.HQSMPO(ansatz: Ansatz | Circuit, max_bond_dimension: int = None, initial_state: Circuit = None, progress: bool = True, stab_engine: StabilizersEngine = None, tn_engine: TensorNetworkEngine = None, head_synthesis: str | HeadSynthesis = 'rustiq', light_cone: bool = False)[source]

Bases: HSMPO

Hybrid Quantum Stabilizer Matrix Product Operator: an HSMPO whose dressed rotations are split into a resynthesised head and an MPO tail, with the head measured from a finite shot budget.

The tail needs a tensor-network engine that can conjugate an operator and export it as site arrays (conjugate_operator(), operator_site_arrays()), such as QuimbEngine.

Parameters:
  • head_synthesis – how the head is resynthesised, a HeadSynthesis such as ExtractionSynthesis(connectivity="line"), or the name of one with its default options: "rustiq" (default), "extraction" or "cnot_ladder".

  • light_cone – drop the rotations the observable cannot see, from the head the device runs and from the tail that is folded, see relevant_rotations(). Exact, and off by default.

build_post_head_mpo(observable: str, cut_index: int, max_bond_dimension: int = -1, residual: Tableau | None = None)[source]

The observable with everything after the head folded in, as an MPO.

Heisenberg picture: the Clifford part, the tail rotations [cut_index:] and, optionally, a Clifford residual are moved into the observable, so that <O> = sign * <head| operator |head>. The steps are:

  1. backpropagate observable through the Clifford part with stim, O -> sign * O', still a single Pauli string;

  2. if residual R is given, conjugate O' and every tail generator through it. Each one stays a Pauli string, and a generator’s sign goes into its angle. This gives exactly R^dag T^dag O' T R without ever building R as an operator;

  3. turn O' into an MPO and conjugate it by the tail rotations, innermost first, truncating each step to max_bond_dimension.

Without residual the MPO pairs with the exact head state. With it, the MPO pairs with ResynthesizedHead.circuit run alone, so the device skips the residual’s gates.

Callers:

  • expectation_at_cut(method="simulation") and tail_truncation() use it as the classical reference;

  • the "pauli" route passes no residual. It samples Pauli strings from the MPO and folds each sampled string through R afterwards (fold_pool_through_tableau()), which is cheaper and unaffected by truncation;

  • the "shadows" route passes residual under tail_handling="fold", because its estimator contracts the whole MPO, so R has to be inside it. The price is usually more Pauli weight, and therefore a higher shadow variance.

Parameters:
  • observable – a Pauli string (qubit-0-leftmost).

  • cut_index – the split point; only rotations [cut_index:] are folded.

  • max_bond_dimension – bond cap for each conjugation. -1 means self.max_bond_dimension, None means untruncated.

  • residual – the Clifford residual R to fold in, typically ResynthesizedHead.residual_tableau. None leaves it out.

Returns:

the folded MPO and the +-1 sign picked up by the Clifford backpropagation and, if given, the residual fold.

Return type:

(operator, sign)

expectation_at_cut(observable: str | list | dict | SymbolicHamiltonian, cut_index: int, method: str | MeasurementMethod = 'pauli', n_shots: int | None = None, epsilon: float | None = None, backend=None, max_bond_dimension: int | None = -1, seed: int | None = None, **method_options) → ExpectationResult[source]

Resynthesise the head, build the measurement circuits, run them and recombine the results, in one call: plan(), then run_plan() on backend, then the method’s estimate. To run the circuits on a device and post-process later, call those three stages separately.

This class is meant for hardware: use a measurement method, which runs the head exactly on a device (or simulator) and keeps only the tail classical. "simulation" instead contracts the head, as a truncated MPS, against the tail MPO, entirely classically. It is a reference for validating the hardware methods, or for comparing a device run against the classical split; it is not a measurement route, and at large scale it is exactly the computation the hardware methods exist to avoid.

Parameters:
  • observable – a Pauli string (qubit-0-leftmost) or a SymbolicHamiltonian. A Hamiltonian folds one tail MPO per term but emits a single set of circuits, since the head does not depend on the observable, and pools Pauli strings shared between terms so each is measured once with the summed coefficient.

  • cut_index – the split point.

  • method – a MeasurementMethod, e.g. ClassicalShadows(tail_handling="fold"); or the name of one, "pauli" or "shadows", built with method_options; or "simulation". "simulation" is classical, see above and _simulate_at_cut(): it needs no resynthesis, backend or shots, and ignores seed.

  • n_shots – a fixed shot budget. Exactly one of this and epsilon for the hardware methods; neither for "simulation".

  • epsilon – a target standard error, which sizes the shot budget from the per-route variance predictor.

  • backend – anything with execute_circuits(circuits, nshots). Defaults to StatevectorExactSimulator.

  • max_bond_dimension – bond cap for every tail fold; -1 means self.max_bond_dimension. With "simulation" the head MPS is capped at self.max_bond_dimension.

  • seed – RNG seed for Pauli sampling and random shadow bases.

  • method_options – options of a method given by name, e.g. n_string_samples for "pauli" or tail_handling for "shadows"; see each method’s class.

Raises:
  • ValueError – on an unknown method, if neither or both of n_shots and epsilon are given for a hardware method, or if either is given with method="simulation".

  • TypeError – on method_options the method does not take.

head_synthesis: str | HeadSynthesis = 'rustiq'
light_cone: bool = False
plan(observable: str | list | dict | SymbolicHamiltonian, cut_index: int, method: str | MeasurementMethod = 'pauli', n_shots: int | None = None, epsilon: float | None = None, max_bond_dimension: int | None = -1, seed: int | None = None, out_folder=None, **method_options) → MeasurementPlan[source]

Build the measurement circuits for observable at cut_index, without running them, and save them as OpenQASM unless out_folder is False.

This is the first of the three stages expectation_at_cut() chains, exposed so the circuits can run anywhere, e.g. on a real device: run the saved circuits, then pass the counts and the returned plan to the method’s estimate (or estimate()).

Only the circuits and shots are saved, not the returned plan, which estimation needs. Building it again takes the same model, the same arguments and a fixed seed. Even then the residual’s gates can differ, so the saved circuits are the ones to run: never replace them with those of a rebuilt plan.

Parameters:
Returns:

A MeasurementPlan.

Raises:

ValueError – on an unknown method, if neither or both of n_shots and epsilon are given, or if the circuits are saved (out_folder is not False) without a seed.

relevant_rotations(observable: str | list | dict | SymbolicHamiltonian) → Tuple[int, ...][source]

Indices of the dressed rotations inside the light cone of observable.

Going backwards from the observable (a Pauli string in the dressed frame, per term), a rotation matters only if its string anticommutes with the observable or with a later rotation that matters. Any other rotation commutes with everything between itself and its own inverse in <psi| U^dag O U |psi>, and cancels: removing it changes nothing. For an observable with several terms the union is returned, which is what a head shared by all the terms has to keep.

Cheap (commutation of Pauli strings only) and exact. With a truncated tail it stays consistent with the truncation: the rotations removed are those that commute with the exact folded observable.

resynthesize_head(cut_index: int, synthesis: str | HeadSynthesis | None = None, observable: str | list | dict | SymbolicHamiltonian | None = None) → ResynthesizedHead[source]

Resynthesise the head rotations [0:cut_index) into a runnable circuit plus a pure-Clifford residual.

If rustiq is asked for but not installed, this warns and falls back to CnotLadderSynthesis.

Cached on the head’s dressed rotations and the synthesis (see _resynthesize()), so repeated calls at the same cut, e.g. from expectation_at_cut() for several observables or methods, resynthesise once, while new parameters give new rotations and hence a fresh resynthesis. Only an immutable description of the head is cached: every call returns a fresh circuit and its own copy of the residual_tableau, so modifying them, or a plan circuit sharing their gates, never reaches a later call.

Parameters:
  • cut_index – the split point.

  • synthesis – a HeadSynthesis or the name of one (default: the instance’s head_synthesis).

  • observable – keep only the head rotations inside the light cone of this observable (relevant_rotations()). The head is then valid for this observable only. None keeps them all.

Raises:

ValueError – on an unknown synthesis name.

tail_truncation(observable: str, cut_index: int, reference_max_bond: int | None = None, exact: bool = True, residual: Tableau | None = None, with_expval: bool = False, max_bond_dimension: int | None = -1) → TailTruncation[source]

Quantify how closely the truncated tail fold approximates the exact one.

By default only operators are compared: the tail fold truncated to max_bond_dimension against a reference fold truncated to reference_max_bond, with no head state built. The truncation is strongly observable-dependent, because the tail is folded onto the target observable: the same circuit, cut and bond cap can be lossless for one observable (e.g. one outside the tail’s backward light cone, which stays a single Pauli string) and heavily truncated for another. Re-assess it for every observable, or every Hamiltonian term.

Parameters:
  • observable – a Pauli string (qubit-0-leftmost).

  • cut_index – the split point.

  • reference_max_bond – bond cap for the reference fold when exact=True; None means untruncated.

  • exact – build the reference fold and report relative_frobenius_error. When False, report only the reference-free fidelity_estimate.

  • residual – forwarded to build_post_head_mpo() for both folds, to assess the fold tail_handling="fold" actually measures.

  • with_expval – also build the exact head state and report expval_abs_error. Needs exact=True.

  • max_bond_dimension – bond cap for the fold under test. -1 means self.max_bond_dimension, None means untruncated.

Returns:

A TailTruncation. fidelity_estimate is always set, relative_frobenius_error only with exact=True, and expval_abs_error only with with_expval=True; the others are None.

Raises:
  • ValueError – for with_expval without exact.

  • NotImplementedError – for with_expval with residual: the expval_abs_error of a folded tail needs the device head state R^dag |head>, which is not built here.

class mpstab.evolutors.hqsmpo.ResynthesizedHead(circuit: object, residual_tableau: object, residual_gates: tuple, n_gates: int, n_two_qubit_gates: int, cut_index: int, method: str)[source]

Bases: object

A head circuit resynthesised for hardware, plus its Clifford residual.

Returned by HQSMPO.resynthesize_head().

Variables:
  • circuit (object) – a runnable qibo Circuit, without measurement gates.

  • residual_tableau (object) – the Clifford residual as a stim.Tableau.

  • residual_gates (tuple) – the same residual as a gate list, for tail_handling="append_to_head_circuit".

  • n_gates (int) – gates in the head.

  • n_two_qubit_gates (int) – two-qubit gates in the head.

  • cut_index (int) – the split point the head came from.

  • method (str) – the name of the synthesis that produced it, e.g. "extraction"; "cnot_ladder" when rustiq was asked for but is not installed.

circuit: object
cut_index: int
method: str
n_gates: int
n_two_qubit_gates: int
residual_gates: tuple
residual_tableau: object
class mpstab.evolutors.hqsmpo.TailTruncation(fidelity_estimate: float, relative_frobenius_error: float | None, expval_abs_error: float | None)[source]

Bases: object

How closely the truncated tail fold approximates the exact one, cheapest view first. Returned by HQSMPO.tail_truncation().

The first two fields compare operators only. They depend on the observable the tail is folded onto, not on the head state.

Variables:
  • fidelity_estimate (float) – ||O_approx||_F**2 / 2**n, a norm-ratio estimate needing only the working truncation, with no exact reference built.

  • relative_frobenius_error (float | None) – ||O_approx - O_exact||_F / ||O_exact||_F; None unless exact=True was requested.

  • expval_abs_error (float | None) – |<O_approx> - <O_exact>| on the exact head state; None unless with_expval=True was requested.

expval_abs_error: float | None
fidelity_estimate: float
relative_frobenius_error: float | None

Gradients

Analytic gradients of the HSMPO surrogate, whose cost does not grow with the number of parameters (one forward pass and one backward pass), instead of the two shifted circuits per parameter of the parameter-shift rule. They plug into any optimizer; the Training a VQE with analytic gradients tutorial trains a VQE with them.

Analytic gradients of the HSMPO surrogate, from the sign-flip rule of its faults.

In the Clifford frame the state is |psi> = R_R ... R_1 |init>, with dressed rotations R_j = exp(-i phi_j/2 G_j), and the observable is sum_t c_t s_t P_t once dressed. Since dR_j/dphi_j = -(i/2) G_j R_j, and R_k G_j = G_j R~_k with R~_k the rotation at angle -phi_k when G_k anticommutes with G_j and R_k itself otherwise:

df/dphi_j = sum_t c_t s_t Im <psi| P_t G_j |psi~_j>,

where |psi~_j> is the chain with the angles of the later rotations anticommuting with G_j negated: the sign pattern a Pauli fault G_j right after rotation j produces in mpstab.models.noise. It equals the parameter-shift rule exactly, with one transition amplitude per term in place of two shifted circuits. Read backwards it is the adjoint method: with |psi_j> the state after rotation j and T_j the rest of the chain, G_j T~_j = T_j G_j turns each term into Im <lambda_j| G_j |psi_j>, where the costate lambda_j = T_j^dag O |psi> follows from one backward pass.

A circuit parameter theta reaches the chain through the dressing sign, phi_j = sign_j theta, so df/dtheta sums sign_j df/dphi_j over the rotations of the parameter’s gate: one per magic gate, and one per occurrence of a gate object queued several times.

Not covered here: gradients under noise (an average over fault patterns of the XOR of fault and parameter rows), and the parameters of the head that HQSMPO runs on hardware, which still need shifted circuits.

class mpstab.evolutors.gradient.AnalyticGradient(values: ndarray, value: float, n_rotations: int, fidelities: ndarray)[source]

Bases: object

Result of analytic_gradient().

Attributes

valuesnumpy.ndarray

The derivative of the expectation value with respect to each requested parameter, in the order requested.

valuefloat

The expectation value itself, on the same (light-cone-restricted) chain, so a training step needs no separate evaluation.

n_rotationsint

Rotations applied to an MPS: the base chain plus every shifted tail.

fidelitiesnumpy.ndarray

Truncation fidelity of the base state, then, with "adjoint", the weight the costate kept through its backward pass, or, with "flips", the fidelity of each shifted state in the order they were built. With a bond-dimension cap, the gradient error is set by how far these fall below 1.

mpstab.evolutors.gradient.analytic_gradient(hsmpo, observable: str | list | dict | SymbolicHamiltonian, parameters: Sequence[int] | None = None, light_cone: bool = True, method: str = 'adjoint', costate_bond: int | None = None, groups: int = 1, n_workers: int | None = None) → AnalyticGradient[source]

Gradient of hsmpo.expectation(observable) with respect to the circuit parameters, as returned by hsmpo.get_parameters().

Two evaluations of the same identity are available:

  • "adjoint": since G_j T~_j = T_j G_j for the tail T_j after rotation j, each derivative is Im <lambda_j| G_j |psi_j> with psi_j the checkpoint after rotation j and lambda_j = T_j^dag O |psi>. One forward pass stores the checkpoints, and one backward pass of the costate lambda gives every derivative: about 2 R rotations for R rotations in the chain, whatever the number of parameters. O |psi> is a sum of states, so the costate is compressed, by default to twice the state’s bond cap. Beyond that the error is set by the state’s own truncation: like any gradient built from overlaps, it is first order in the state error, where an energy (and so the parameter-shift rule) is second order.

  • "flips": each derivative is Im <psi| O G_j |psi~_j>, with psi~_j the chain under the sign pattern of a fault G_j. Each distinct pattern re-applies only the tail after its first flipped rotation, visited in lexicographic order so consecutive patterns share their prefix, and a rotation that commutes with every later one costs one expectation value on the base state. It needs no costate, so at equal bond dimension it is the more accurate, but it applies O(P R) rotations for P parameters.

Parameters

hsmpoHSMPO

The surrogate, with its parameters already set.

observableObservable

A Pauli string or any other format pauli_terms() accepts.

parameterssequence of int, optional

Indices of the parameters to differentiate, into hsmpo.get_parameters(). All of them by default.

light_conebool, optional

Drop the rotations outside the observable’s light cone (pauli_light_cone()) first. This is exact: a parameter whose rotations all fall outside has zero derivative.

methodstr, optional

"adjoint" (default) or "flips".

costate_bondint, optional

Bond-dimension cap of the costate with "adjoint". Defaults to twice hsmpo.max_bond_dimension, and to no cap when the state has none. Capping it at the state’s own bond is about twice as fast, for roughly twice the gradient error; a larger cap gains nothing, since the state’s truncation then dominates.

groupsint, optional

Split the observable’s terms into this many blocks of neighbouring terms (by the centre of their support) and differentiate each block on its own light cone; the gradient is linear in the terms, so the sum is exact. A block’s cone is narrower than the union of all of them and carries less entanglement: once the union saturates the bond cap, blocks are faster and, at the same cap, more accurate. While the bond stays below the cap the union is cheaper, since the blocks’ cones overlap. One block (default) uses the union.

n_workersint, optional

Processes the blocks run on, min(groups, os.cpu_count()) by default. The pool is started on first use, which costs about a second per process, and kept for later calls with the same n_workers, so a training loop pays it once. Each process holds the checkpoints of its blocks, so fewer workers bound the memory.

Returns

AnalyticGradient

Raises

ValueError

If a requested parameter has no rotation in the chain: its gate sits at a Clifford angle (a multiple of pi/2, zero included) and was absorbed into the tableau, or the ansatz builds its rotations from copies of its gates. Also on an unknown method.

NotImplementedError

If the tensor-network engine does not compute transition amplitudes, or, with "adjoint", Pauli sums applied to a state.

Examples

from qibo import Circuit, gates
from mpstab import HSMPO

circuit = Circuit(2)
circuit.add(gates.RY(0, theta=0.4))
circuit.add(gates.CNOT(0, 1))
circuit.add(gates.RX(1, theta=0.3))
print(HSMPO(circuit).gradient("ZZ"))

Usage Example:

import numpy as np
from mpstab import HSMPO
from mpstab.models.ansatze import HardwareEfficient

np.random.seed(0)
surrogate = HSMPO(HardwareEfficient(nqubits=6, nlayers=2))
gradient = surrogate.gradient({"ZZIIII": 1.0, "IIXXII": 0.5})
print(gradient.shape)  # one derivative per parameter: (12,)

Optimization

Optimization of an HSMPO’s MPS with DMRG, and the fused adjoint kernel of its analytic gradient.

mpstab.evolutors.optimization.adjoint_kernel(engine, initial_state, generators, angles, sites, observables, weights, max_bond, costate_bond)[source]

The expectation value and its derivative with respect to each rotation angle of a dressed-rotation chain, in one forward and one backward pass.

With psi_j the state after rotation j, T_j the rest of the chain and O = sum_t w_t P_t, the derivative with respect to the angle of rotation j is Im <lambda_j| G_j |psi_j> / <psi|psi>, with the costate lambda_j = T_j^dag O |psi>. The forward pass keeps every psi_j; the backward pass applies the inverse rotations to the costate and takes one transition amplitude per rotation in sites.

Everything runs on the windowed kernels of _mps_kernels, on plain lists of site arrays: a checkpoint is a shallow copy of the list, since the kernels replace arrays rather than write into them.

Parameters:
  • engine – a QuimbEngine on the numpy backend.

  • initial_state – the initial MPS, left untouched.

  • generators – the chain, exp(-i angle/2 generator) in order.

  • angles – the chain, exp(-i angle/2 generator) in order.

  • sites – increasing indices of the rotations to differentiate.

  • observables – the dressed observable sum_t w_t P_t.

  • weights – the dressed observable sum_t w_t P_t.

  • max_bond – bond cap of the state.

  • costate_bond – bond cap of the costate.

Returns:

the normalized expectation value, the derivative per rotation (zero outside sites), the rotations applied, and the truncation fidelities of the state and of the costate.

Return type:

(value, derivatives, n_rotations, fidelities)

mpstab.evolutors.optimization.minimize_expectation_dmrg(hsmpo, observables: str | list | dict | SymbolicHamiltonian, bond_dims: int | list = None, cutoff: float = 1e-09, tol: float = 1e-06, max_sweeps: int = 10, verbosity: int = 1)[source]

Minimize an observable over MPS tensors with two-site DMRG.

Every Hamiltonian term is first backpropagated through the HSMPO’s Clifford circuit, which is what makes the MPO cheaper here than in plain DMRG: the Clifford part is absorbed into the observable rather than represented. The HSMPO’s cached MPS is the starting guess, and is replaced by the optimized state on return. The sweeps themselves run on the tensor-network engine (minimize_energy()).

Parameters:
  • hsmpo – the HSMPO to optimize.

  • observables – the Hamiltonian, in any format pauli_terms() accepts.

  • bond_dims – max bond dimension per sweep, or one value for all. Defaults to a gradual [10, 20, 50, 100, 200] growth.

  • cutoff – SVD truncation cutoff.

  • tol – energy convergence tolerance.

  • max_sweeps – maximum number of sweeps.

  • verbosity – DMRG verbosity, 0 to 2.

Returns:

A dict with ground_state, energy, converged, num_sweeps and energy_history. Energies include the Hamiltonian’s constant offset and identity terms.

Raises:

ValueError – if the Hamiltonian has no non-identity terms.

Utilities

Helpers shared by the evolutors.

mpstab.evolutors.utils.FIXED_ANGLES = {'t': 0.7853981633974483}

Rotation angles of magic gates that carry no parameter.

mpstab.evolutors.utils.GATE_GENERATORS = {'rx': 'X', 'rxx': 'X', 'ry': 'Y', 'ryy': 'Y', 'rz': 'Z', 'rzz': 'Z', 't': 'Z'}

The Pauli each supported magic gate rotates about, on every qubit it targets: RZZ(theta) = exp(-i theta/2 Z Z) has generator "ZZ" on its two qubits.

mpstab.evolutors.utils.gate_angle(gate) → float[source]

The rotation angle of a magic gate, including fixed-angle ones like T.

mpstab.evolutors.utils.gate_generator(gate, nqubits: int) → str[source]

The full-width Pauli string generating gate’s rotation.

Raises:

ValueError – if gate is not one of the supported rotations.

For more practical examples, see: