Skip to content

QAOA And VQE

CASCAQit provides one local workflow for problem declaration, variational optimization, final sampling, decoding, and reporting. The short path uses root imports:

from cascaqit import LocalBackend, OptimizerConfig, QAOA, QUBOProblemIR, visualize

problem = QUBOProblemIR.from_terms(
    problem_id="qubo.demo",
    linear_terms={"x0": -1.0, "x1": -1.0},
    quadratic_terms={("x0", "x1"): 2.0},
)
result = QAOA(problem, layers=2).run(
    backend=LocalBackend(seed=7),
    optimizer=OptimizerConfig(method="COBYLA", max_iterations=40, seed=7),
)
visualize(result, output="qaoa.html")

run() builds a canonical parameterized Circuit, calls the local Backend once for every objective evaluation, selects the lowest observed energy, and performs one separate fixed-seed final sampling Job. The returned VariationalResult keeps every evaluation and source ResultIR; termination.nfev therefore matches the evaluation and objective-Result counts. COBYLA requires an effective objective-evaluation budget of at least parameter_count + 2; smaller values fail before a Backend call so SciPy versions cannot silently increase the workload. Read termination.reason for the stable outcome; termination.status and termination.message retain optimizer-specific evidence.

Inputs

QAOA accepts GraphProblemIR, MWISProblemIR, QUBOProblemIR, or IsingModelIR. A graph is converted to a maximum-independent-set QUBO with a penalty greater than one. MWIS uses positive node weights and a penalty strictly above the weighted vertex-removal threshold. VQE accepts QUBO, Ising, or PauliHamiltonian. Use HamiltonianTerm with PauliI, PauliX, PauliY, PauliZ, or PauliProduct for a general operator.

QAOA exposes its structure before gate expansion. build_plan() retains each layer's Z/ZZ terms and parameter references; logical_schedule() uses deterministic edge coloring so two-qubit operations in one color layer never share a qubit:

from cascaqit.compiler import QAOALogicalScheduler

qaoa = QAOA(problem, layers=2)
plan = qaoa.build_plan()
scheduled = qaoa.logical_schedule()

assert scheduled.schedule.schedule_stage == "canonical"
assert scheduled.schedule.target_snapshot_hash is None
assert all(
    group.conflict_check.passed
    for layer in scheduled.layer_evidence
    for group in layer.edge_color_groups
)

native = QAOALogicalScheduler().lower_to_native(
    scheduled,
    strategy="cx_rz_cx",
    target_snapshot_hash="a" * 64,
)
assert native.schedule_stage == "native"

These schedules describe logical concurrency, not threads or physical pulse overlap. Native lowering is an explicit strategy choice. Routing and physical scheduling with durations, channels, and calibration are not implemented.

Run qaoa_logical_scheduling.py with --output artifacts/qaoa_logical_scheduling.html to inspect a four-variable plan whose first color group contains two conflict-free ZZ interactions and save the explicitly lowered Native schedule.

Use ProblemCompiler.compile(mode="digital", algorithm="vqe", ...) when Graph, MIS, MWIS, QUBO, or Ising workflows also need shared Target analysis, Problem decoding, bounded baselines, and standard Problem reports. A fixed-depth Unified compile accepts the default template, a configured HardwareEfficientAnsatz, a fixed-cardinality CardinalityPreservingAnsatz, or a parameterized custom Circuit. Standalone VQE remains useful for general Pauli Hamiltonians that have no Problem decoder.

HardwareEfficientAnsatz supports any non-empty unique sequence of RX, RY, and RZ rotations plus linear or circular CX entanglement. Import HardwareEfficientAnsatz, build_vqe_ansatz, and transfer_vqe_parameters from cascaqit.algorithms; these are advanced owner-package APIs, not package-root exports.

When the exact number of selected variables is known, restrict VQE to that computational-basis subspace:

from cascaqit.algorithms import (
    CardinalityConstraint,
    CardinalityPreservingAnsatz,
)

ansatz = CardinalityPreservingAnsatz(
    constraints=(
        CardinalityConstraint(
            qubits=("asset_0", "asset_1", "asset_2", "asset_3"),
            weight=2,
        ),
    ),
    free_rotation_axes=("ry",),
    entanglement="linear",
)
compiled = ProblemCompiler().compile(
    problem,
    mode="digital",
    algorithm="vqe",
    target=target,
    layers=2,
    ansatz=ansatz,
)

Each group starts from a deterministic basis state with the requested weight. Givens rotations move amplitude only within

span⁡ ⁣{∣01⟩,∣10⟩}, \operatorname{span}\!\left\{\lvert 01\rangle,\lvert 10\rangle\right\},

while CZ gates correlate groups without changing computational-basis occupation. Qubits outside every group retain the rotations listed in free_rotation_axes. Groups must not overlap, and every grouped qubit must belong to the Hamiltonian logical_order.

This Definition preserves only the declared Hamming weights. It does not infer constraints from QUBO coefficients or metadata, and it does not enforce capacity, exclusion, sector, or other business rules. The Hamiltonian and all penalties remain unchanged, and the Problem decoder still recomputes each candidate from the source objective. Ideal execution preserves cardinality. Noise may leave the subspace; CASCAQit does not filter or replace raw counts.

Completed fixed-cardinality runs expose cardinality_subspace on both VariationalResult and ProblemExecutionResult. The evidence records each group's qubits, target weight, observed weight distribution, preservation rate, and, for sampled results, preserved and violating shots. Exact evaluate() results use complete probabilities instead. The standard Algorithm and Problem reports render the same saved evidence without rerunning the Backend.

OptimizerConfig supports derivative-free COBYLA, Nelder-Mead, and Powell, gradient-based L-BFGS-B, and native SPSA. Set max_evaluations when objective evaluations must be bounded independently of optimizer iterations. Initial parameters and bounds are validated before the first Backend call; omitted initial values are generated deterministically from the algorithm configuration and seed.

Native SPSA

SPSA estimates every parameter component from simultaneous plus/minus perturbations. directions_per_iteration controls how many independently drawn Rademacher directions share one center. The default is one direction and preserves the original two-point update. With multiple directions, CASCAQit computes one gradient per complete plus/minus pair, averages the direction gradients, and records the component standard error across directions. A sampled VQE objective can also repeat each logical parameter point and use the pooled mean; every repeat executes the complete QWC measurement plan.

from cascaqit import OptimizerConfig, SPSAConfig, VQE

result = VQE(hamiltonian, layers=2).run(
    optimizer=OptimizerConfig(
        method="SPSA",
        max_iterations=20,
        max_evaluations=122,
        seed=7,
        spsa=SPSAConfig(
            learning_rate=0.2,
            perturbation=0.1,
            directions_per_iteration=3,
        ),
    ),
)

Each start evaluates the initial center, every complete direction, and the final updated center. For K=directions_per_iteration and objective_repeats=r, one iteration is an atomic 2Kr2Kr unit and the minimum one-iteration budget is (2+2K)r(2+2K)r. SPSAObjectiveEstimateIR records ordered offsets, raw energies, pooled mean, repeat standard error, and the repeat stop reason. Each SPSADirectionIR retains its perturbation, parameters, two pooled estimates, and direction gradient. SPSAIterationIR retains the averaged gradient, its component standard error when K≥2K\ge2, projected update, and update norm. Import SPSADirectionIR from cascaqit.algorithms; it is not a package-root export. A fixed start seed reproduces the direction sequence and every repeated measurement.

Multiple directions reduce dependence on a single random perturbation but multiply the objective and Backend cost. The component standard error describes disagreement among the direction gradients; it is not an energy uncertainty, stopping rule, or proof that K>1K>1 will outperform the default. Adaptive repeats reserve the minimum cost of every remaining direction and the final center before adding another balanced plus/minus repeat. Run python3 examples/user/vqe_multidirection_spsa_workflow.py to compare exact and finite-shot execution with the same three-direction configuration.

The native path supports deterministic ideal-state and exact-density Digital objectives. Standalone VQE and compiled Unified Problem VQE may instead pass PauliMeasurementConfig to optimize finite-shot Pauli estimates with native SPSA or Adam under ideal execution or a canonical NoiseModel. Sampled noise supports Digital preparation, gate, idle, crosstalk, and readout channels with auto, density_matrix, or trajectory simulation. SPSA can use fixed or bounded standard-error-driven objective repeats. Adam can repeat the entire sampled parameter-shift gradient, pool each QWC group, and stop at a bounded uncertainty target or hard budget. It may also require consecutive update-size and gradient-uncertainty thresholds. Both optimizers support uniform, coefficient-L1, or pilot-variance group allocation, caller-supplied tensor-product readout mitigation, independent candidate confirmation, and final sampling under one execution context. General error mitigation, sampled QAOA, per-occurrence adaptive gradients, Analog/Hybrid gradients, and live hardware are not supported. Reports render the actual measurements, uncertainty, stop reasons, and Backend cost without rerunning the optimizer.

Learning-Rate Scale Calibration

A fixed learning_rate can produce very different update sizes after changing the Hamiltonian energy unit, the Ansatz dimension, or the initial point. Enable local scale calibration when the desired first-step parameter RMS is easier to specify than the raw SPSA gain:

from cascaqit import SPSAConfig, SPSALearningRateCalibrationConfig

spsa = SPSAConfig(
    learning_rate=None,
    perturbation=0.1,
    learning_rate_calibration=SPSALearningRateCalibrationConfig(
        directions=5,
        target_update_rms=0.05,
        gradient_rms_floor=1e-8,
        max_learning_rate=2.0,
    ),
)

Before iteration zero, CASCAQit evaluates directions complete plus/minus pairs at the initial point and averages their SPSA gradients. If that vector has RMS g_rms, it derives the scale

a=utarget(1+A)αgRMS, a = \frac{u_{\mathrm{target}}(1+A)^{\alpha}}{g_{\mathrm{RMS}}},

where A and alpha are the configured stability constant and learning-rate exponent, and u_target is target_update_rms. The first scheduled learning rate is therefore

a0=utargetgRMS. a_0 = \frac{u_{\mathrm{target}}}{g_{\mathrm{RMS}}}.

A gradient below gradient_rms_floor or a derived scale above max_learning_rate fails before a formal iteration.

For fixed repeats, the number of additional objective evaluations per optimizer start is

Ncalibration=2dR, N_{\mathrm{calibration}} = 2dR,

where d is directions and R is objective_repeats. Adaptive sampled objectives keep every plus/minus pair balanced and reserve the minimum cost of calibration, required iterations, and the final center before starting work. Evaluation and Backend limits include this cost. SPSALearningRateCalibrationIR in cascaqit.algorithms saves the declaration-order parameter names, directions, pooled objectives, averaged gradient, RMS, derived scale, offsets, and projection status; JSON restoration recomputes the evidence and replays its Rademacher stream from the start seed. Algorithm and Problem reports show the same saved facts.

Scaling the complete Hamiltonian by a positive factor s gives

∇E′=s∇E,a′=as. \nabla E' = s\nabla E, \qquad a' = \frac{a}{s}.

With the same seed and no changed bounds behavior, the parameter trajectory is invariant within floating-point tolerance. This property removes one energy-unit dependency; it does not choose perturbation, schedule exponents, direction count, repeats, stopping thresholds, or a suitable Ansatz. It also does not imply a lower final energy, convergence, a ground state, or quantum advantage. Run python3 examples/user/vqe_learning_rate_calibration_workflow.py to compare fixed gain, calibrated gain, and a 25-times-scaled Hamiltonian.

Online Stability Stopping

Set SPSAConfig.stopping when the optimizer should stop after a complete window satisfies explicit engineering thresholds:

from cascaqit import SPSAConfig, SPSAStoppingConfig

spsa = SPSAConfig(
    learning_rate=0.2,
    perturbation=0.1,
    directions_per_iteration=3,
    stopping=SPSAStoppingConfig(
        window_size=3,
        min_iterations=5,
        objective_range_tolerance=0.02,
        update_norm_tolerance=0.01,
        gradient_norm_tolerance=0.1,
        gradient_standard_error_norm_tolerance=0.05,
    ),
)

After each complete iteration, CASCAQit checks the range of the window's plus/minus center proxies, the largest update norm, and the largest averaged-gradient L2 norm. The optional direction-standard-error check requires at least two directions. A sampled objective may also set sampled_standard_error_tolerance; it requires objective_repeats >= 2 and checks every plus/minus pooled standard error in the window. Invalid or unreachable configurations fail before the first objective Job.

The first complete passing window terminates with reason="stability_reached". Legacy OptimizerConfig.tolerance still has priority when both rules pass in the same iteration. Neither check adds a Backend Job, and the optimizer still evaluates the final center before ranking points or confirming sampled candidates. spsa_stopping_evidence records the window, objective proxies, observed values, thresholds, statuses, and sample counts. The standard Algorithm and Problem reports show this evidence separately from the final-center objective and actual cost.

Online stopping is disabled by default. stability_reached means only that the configured thresholds passed; it does not prove a ground state, global optimum, strict convergence, or quantum advantage. Run python3 examples/user/vqe_online_stopping_workflow.py to compare an early stop with a run that reaches its iteration budget.

Finite-Shot Pauli Energy

Use evaluate_sampled() when a fixed VQE parameter point must be estimated from terminal measurements instead of an exact state or density matrix:

from cascaqit import PauliMeasurementConfig, VQE, visualize

vqe = VQE(hamiltonian)
sampled = vqe.evaluate_sampled(
    parameters,
    measurement=PauliMeasurementConfig(
        shots_per_group=4096,
        allocation="coefficient_l1",
    ),
    seed=7,
)
visualize(sampled, output="vqe-sampled.html")

CASCAQit assigns the Hamiltonian terms to stable first-fit qubit-wise commuting (QWC) groups. Each group has one local Pauli basis. X uses an H rotation, Y uses S-dagger followed by H, Z needs no rotation, and every group ends with computational-basis measurement. Static allocation executes one LocalBackend Job per group; pilot-variance allocation executes a pilot Job and an additional Job per group. The energy is the Hamiltonian constant plus the weighted sample means from all groups.

The default allocation="uniform" executes shots_per_group shots in every group. allocation="coefficient_l1" keeps the same total budget, group_count * shots_per_group, but distributes it according to each group's sum of absolute Hamiltonian coefficients. Every group receives at least two shots, and plan.shots_by_group records the exact integers. This static rule reduces a coefficient-only worst-case variance bound, but it does not inspect the prepared state or guarantee a smaller realized error.

allocation="pilot_variance" uses the same total budget. Each group first receives pilot_shots_per_group; if omitted, the pilot size is one quarter of shots_per_group, capped at 32 and never below 2. At least two shots per group remain for the second stage. CASCAQit estimates each group's single-shot energy variance from the pilot counts and assigns the remaining budget in proportion to the observed standard deviations. If all pilot variances are zero, it falls back to coefficient-L1 weights. plan.shots_by_group contains the executable pilot budget; adaptive_allocation.final_shots_by_group and evaluation.final_shots_by_group contain the final totals. The final estimate pools both stages instead of discarding pilot counts.

Pilot allocation doubles the group Job count and uses a noisy variance estimate, so it is not automatically better for every Hamiltonian or pilot size. A diagonal QUBO usually forms one QWC group; no strategy can redistribute shots across groups in that case.

SampledObjectiveEvaluationIR retains the measurement plan, parameter bind, group seeds, Backend Job and Result identities, counts, runtime allocation, term expectations, per-term standard errors, covariance-aware group energy errors, total energy standard error, shots, and hashes. Group uncertainty is computed from the complete per-shot weighted group energy, so covariance between terms measured from the same bitstring is retained. Pilot and second-stage counts are merged per group before these statistics are recomputed; independent group variances are then added. JSON restoration also reconstructs the runtime allocation from pilot counts and rejects inconsistent evidence.

visualize(sampled) shows the Hamiltonian, source Circuit identity, QWC bases, Job cost, one counts chart per group, Pauli expectations, energy contributions, the standard error, and a 95% normal-approximation interval. It does not call the Backend again and does not claim a global optimum or quantum advantage.

Use the same estimator throughout native SPSA by passing measurement to run():

from cascaqit import SampledSelectionConfig

result = vqe.run(
    optimizer=OptimizerConfig(
        method="SPSA",
        max_iterations=6,
        max_evaluations=70,
        max_backend_executions=140,
        seed=7,
        spsa=SPSAConfig(
            learning_rate=0.2,
            perturbation=0.1,
            objective_repeats=2,
            max_objective_repeats=5,
            objective_standard_error_target=0.02,
        ),
    ),
    measurement=PauliMeasurementConfig(
        shots_per_group=1024,
        allocation="coefficient_l1",
    ),
    sampled_selection=SampledSelectionConfig(
        candidate_count=3,
        repeats_per_candidate=3,
        max_repeats_per_candidate=5,
        shots_per_group=2048,
        max_backend_executions=30,
    ),
    final_shots=256,
)
visualize(result, output="vqe-sampled-spsa.html")

max_evaluations counts actual sampled parameter-point executions, including every adaptive repeat. Six iterations produce 14 logical estimates, so the configured ceiling is

14×5=70 14 \times 5 = 70

evaluations; reaching the target earlier consumes less. The optimizer's max_backend_executions counts QWC group Jobs and must cover complete evaluations. Confirmation has a separate hard Job budget. With two groups, the initial confirmation look costs

3 candidates×3 repeats×2 groups=18 Jobs. 3\ \text{candidates} \times 3\ \text{repeats} \times 2\ \text{groups} = 18\ \text{Jobs}.

Before the first Job, the optimizer requires enough budget for the minimum initial center, one plus/minus pair, and the final center. During execution, it never starts a half pair or spends the reserved final-center budget.

Without sampled_selection, final sampling uses the parameter binding with the lowest pooled optimization mean. With it, CASCAQit ranks distinct bindings by the same pooled estimates and independently measures the first candidate_count points. repeats_per_candidate defines the complete initial look. Setting a larger max_repeats_per_candidate enables sequential confirmation until confidence separation, the repeat ceiling, or the Backend budget.

best_evaluation is the stable source evaluation for the lowest pooled optimization estimate; selected_evaluation is the independently confirmed point used for final sampling and may differ. The result retains every raw optimization repeat and every confirmation repeat. Confirmation work is excluded from optimizer nfev and reported separately from final sampling.

Sequential confirmation adapts repeat counts, not the allocation within a saved QWC plan, and it never reuses SPSA perturbation samples. Confirmation preserves the optimization measurement's allocation strategy while allowing a different reference shots_per_group. A normal-approximation result covers only the saved candidate set under the configured procedure; it does not establish a global optimum or quantum advantage. optimality_claim remains not_claimed.

Fixed-point, SPSA, and Adam paths support ideal or noisy local Digital execution with uniform, static coefficient_l1, or two-stage pilot_variance QWC allocation. Sampled optimization is available through standalone VQE and Unified Problem Digital VQE. SPSA supports fixed or bounded standard-error-driven objective repeats. Adam supports fixed or bounded adaptive complete-gradient repeats and optional uncertainty-aware engineering stopping. Unified single-run and repeated layer experiments accept either optimizer when independent candidate confirmation is configured. Every group result retains its NoiseModel, requested options, SimulationPlan, NoiseReport, raw counts, seed, Job, Result, and evidence hash. Explicit tensor-product readout mitigation applies to fixed points, optimization, confirmation, gradients, and layer experiments. General commuting-group Clifford diagonalization, sampled optimizers beyond SPSA and Adam, sampled QAOA, standalone single-run layer selection, and live hardware are not supported.

Run python3 examples/user/vqe_noisy_sampled_workflow.py --output-dir artifacts/vqe_noisy_sampled --language en to compare ideal, readout-only, density-matrix, and trajectory estimates at one parameter point and inspect a complete noisy SPSA workflow. The local noise results are model outputs, not a device-accuracy claim.

Readout Mitigation

Readout mitigation is opt-in and calibration-driven. The calibration matrix uses

Am,t=P(measured=m∣true=t), A_{m,t} = P(\text{measured}=m \mid \text{true}=t),

where rows are measured states and columns are prepared states. For a Pauli outcome function, the corrected measurement function on each qubit is

fcorrected=A−Tf. f_{\mathrm{corrected}} = A^{-\mathsf{T}}f.

The estimator combines the factors without constructing a full exponential-size response matrix.

from cascaqit import (
    PauliMeasurementConfig,
    ReadoutCalibration,
    ReadoutMitigationConfig,
)

calibration = ReadoutCalibration.from_probabilities(
    logical_order=("q0", "q1"),
    p01={"q0": 0.03, "q1": 0.04},
    p10={"q0": 0.02, "q1": 0.05},
    source="calibration-reference-a",
)
measurement = PauliMeasurementConfig(
    shots_per_group=2048,
    allocation="coefficient_l1",
    mitigation=ReadoutMitigationConfig(
        calibration,
        max_condition_number=50.0,
    ),
)
evaluation = vqe.evaluate_sampled(
    parameters,
    measurement=measurement,
    noise=noise,
    options=options,
    seed=17,
)

The calibration must cover logical_order exactly and pass the configured total condition-number limit. CASCAQit does not infer calibration from NoiseModel. Linear inversion does not clip corrected quasi expectations to [-1, 1]; clipping would bias the estimator. The result therefore stores raw and mitigated energy, standard error, per-term contribution, per-group statistics, variance amplification, calibration identity, and condition numbers. Raw Backend counts and final computational-basis counts remain unchanged integers.

Passing the same measurement config to VQE.run() or Unified Problem VQE makes SPSA updates, pooled candidate ranking, fixed or sequential confirmation, warm starts, and layer selection use the mitigated objective. One frozen calibration is retained across optimization and confirmation. A lower mitigated bias is not guaranteed: a mismatched or ill-conditioned calibration can increase error or variance. Run PYTHONPATH=src python3 examples/user/vqe_readout_mitigation_workflow.py --output-dir artifacts/vqe_readout_mitigation --language en for a fixed-point comparison and a complete mitigated SPSA workflow.

Paired Sampling Strategy Benchmark

Use benchmark_sampling() when the question is whether a sampled strategy selected useful parameters, rather than whether its reported sample mean happened to be low:

from cascaqit import VQESamplingBenchmarkConfig

benchmark = vqe.benchmark_sampling(
    VQESamplingBenchmarkConfig(
        repeats=3,
        objective_evaluation_budget=12,
        optimizer=OptimizerConfig(
            method="SPSA",
            max_iterations=1,
            spsa=SPSAConfig(learning_rate=0.2, perturbation=0.15),
        ),
        measurement=PauliMeasurementConfig(shots_per_group=128),
        sampled_selection=SampledSelectionConfig(
            candidate_count=2,
            repeats_per_candidate=2,
        ),
        fixed_objective_repeats=2,
        adaptive_objective_repeats=2,
        adaptive_max_objective_repeats=3,
        adaptive_standard_error_target=0.08,
        root_seed=29,
    )
)
benchmark.report("vqe-sampling-benchmark.html")

Each repeat runs exact, sampled_single, sampled_fixed, and sampled_adaptive from the same initial parameters and optimizer seed. The three sampled strategies also share the objective evaluation ceiling, QWC measurement, and candidate-confirmation configuration. Fixed and adaptive repeats consume real evaluations inside that ceiling; they are not collapsed into one logical point for cost reporting.

After a sampled run selects its final parameter binding, CASCAQit performs one independent exact evaluation at that binding. estimator_error compares the selected sampled estimate with this exact check. paired_exact_reference_gap compares the exact energy of the sampled-selected binding with the selected energy from the exact optimizer in the same repeat. Diagnostic exact Jobs are reported separately and do not enter optimizer nfev, Backend limits, or shots.

VQESamplingBenchmarkResult stores every complete VariationalResult, exact check, paired seed, cost account, Student-t interval, and identity. JSON restoration recomputes the errors, paired gaps, cost means, and strategy statistics. The exact optimizer remains a same-Ansatz, same-initialization, fixed-budget reference; it is not a ground-state, global-optimum, or quantum-advantage claim.

Stability And Stopping Diagnosis

Use diagnose_stability() after a native-SPSA VQE run when you need to distinguish a stable terminal window from an optimizer that merely reached its budget:

from cascaqit import VQEStabilityConfig

diagnostic = result.diagnose_stability(
    VQEStabilityConfig(
        window_size=3,
        min_iterations=3,
        objective_range_tolerance=0.02,
        update_norm_tolerance=0.01,
        gradient_norm_tolerance=0.1,
        sampled_standard_error_tolerance=0.03,
    )
)
print(diagnostic.status)
diagnostic.report("vqe-stability.html")

The method reads the saved VariationalResult; it does not call the Backend or optimizer. For each optimizer start, it averages the plus/minus midpoint proxies from every direction in an SPSA iteration, appends the saved final-center objective, and checks the terminal objective range. It also checks the maximum update and averaged-gradient L2 norm in the same iteration window. A sampled run adds the pooled standard errors, actual repeat counts, and repeat stop reasons from every terminal direction plus the final estimate.

stable means every required check passed the configured thresholds. unstable means the trajectory was long enough but at least one check failed. insufficient_evidence means the run was too short or a required value was unavailable. In particular, a single sampled evaluation cannot estimate a repeat standard error and therefore cannot receive a stable sampled diagnosis. Multi-start runs keep separate trajectories, and the overall status follows selected_start_index.

The report shows the diagnosis beside the original termination reason, evaluation count, and Backend cost. Optimizer success does not replace these checks, and a budget stop does not by itself mean the algorithm failed. The diagnosis does not prove a ground state, global optimum, strict mathematical convergence, or quantum advantage. It accepts exact, ideal sampled, and noisy sampled VQE with native SPSA by reading the saved objective statistics; it does not compensate for noise bias. SciPy optimizers and live hardware results are not supported. Run python3 examples/user/vqe_stability_workflow.py for exact and finite-shot examples.

Executable Parameter-Shift Gradients

Standalone QAOA and VQE can evaluate a gradient directly or pass the same execution path to L-BFGS-B:

from cascaqit.algorithms import GradientConfig, OptimizerConfig

gradient = QAOA(problem).gradient(
    {"gamma_0": 0.2, "beta_0": -0.3},
    backend=LocalBackend(seed=7),
    seed=7,
)
result = QAOA(problem).run(
    backend=LocalBackend(seed=7),
    optimizer=OptimizerConfig(
        method="L-BFGS-B",
        gradient=GradientConfig(max_evaluations=4),
        max_evaluations=8,
        max_backend_executions=64,
        seed=7,
    ),
    initial_parameters={"gamma_0": 0.2, "beta_0": -0.3},
)

The planner finds every affine parameter occurrence on RX, RY, and RZ gates. Each occurrence executes two shifted Circuits through LocalBackend; shared algorithm parameters sum all occurrence contributions. ObjectiveGradientIR stores the positive and negative energies, derivative uncertainty, parameter components, complete covariance matrix, L2 norm, shots, Job identities, hashes, and Backend cost. VariationalResult.gradients retains every jacobian callback. termination.nfev, termination.njev, and termination.backend_execution_count separate objective calls, gradient calls, and total Backend work.

VQE can pass PauliMeasurementConfig to gradient() for ideal, noisy, or readout-mitigated finite-shot parameter-shift. The same measurement contract can drive native Adam:

from cascaqit.algorithms import (
    AdamConfig,
    AdamStoppingConfig,
    PauliMeasurementConfig,
    SampledSelectionConfig,
)

result = vqe.run(
    optimizer=OptimizerConfig(
        method="ADAM",
        max_iterations=20,
        gradient=GradientConfig(
            repeats=2,
            max_repeats=5,
            uncertainty_norm_target=0.08,
        ),
        adam=AdamConfig(
            learning_rate=0.05,
            stopping=AdamStoppingConfig(
                window_size=3,
                min_iterations=3,
                update_norm_tolerance=0.01,
                gradient_uncertainty_norm_tolerance=0.08,
            ),
        ),
    ),
    measurement=PauliMeasurementConfig(shots_per_group=256),
    sampled_selection=SampledSelectionConfig(
        candidate_count=3,
        repeats_per_candidate=3,
    ),
)

Each repeat executes every parameter occurrence's positive and negative shift with the complete QWC plan. Pooling merges counts within matching QWC groups before recomputing energies, derivative variance, the full parameter covariance, and

u=tr⁡(Σ). u = \sqrt{\operatorname{tr}(\Sigma)}.

Here, u is uncertainty_norm and Sigma is the complete parameter covariance matrix. Adaptive mode starts checking after repeats, then stops at the target, max_repeats, or the available objective/Backend budget. It never leaves a partial occurrence, one-sided shift, or incomplete QWC group.

Each Adam iteration stores the objective, pooled gradient and covariance, actual repeat count and stop reason, first and second moments, bias correction, step, bounds projection, update norm, and stopping evidence. The second moment is optimizer state, not finite-shot variance. The optional Adam stopping rule requires both configured window conditions; reaching either uncertainty threshold is an engineering status, not proof of convergence. Reports show objective, gradient, candidate-confirmation, and final-sampling costs separately. Run python3 examples/user/vqe_adam_gradient_workflow.py for a fixed-seed comparison of single, fixed-repeat, and adaptive gradients plus uncertainty-aware Adam.

This implementation is parameter-shift, not symbolic, reverse-mode, adjoint, or general automatic differentiation. Sampled gradients and Adam are VQE-only; sampled QAOA, per-occurrence adaptive allocation, Analog/Hybrid gradients, correlated readout, true-device execution, and parallel shift evaluation are not supported. GradientConfig.max_evaluations, GradientConfig.max_objective_evaluations, and OptimizerConfig.max_backend_executions stop before an incomplete gradient repeat or Adam iteration starts.

Deterministic Noisy Digital Optimization

Standalone and Unified Digital QAOA/VQE accept the canonical simulator NoiseModel and SimulationOptions on run(), evaluate(), gradient(), and optimize():

from cascaqit.simulators import NoiseChannel, NoiseModel, SimulationOptions

noise = NoiseModel(
    "noise.optimization",
    (
        NoiseChannel.gate(0.01),
        NoiseChannel.readout(0.02),
    ),
)
options = SimulationOptions(method="density_matrix")

result = QAOA(problem).run(
    optimizer=OptimizerConfig(method="COBYLA", max_evaluations=8),
    noise=noise,
    options=options,
    final_shots=256,
    seed=7,
)
gradient = QAOA(problem).gradient(
    {"gamma_0": 0.2, "beta_0": -0.3},
    noise=noise,
    options=options,
    seed=7,
)

At least one preparation, gate, idle, or crosstalk channel is required for noisy optimization. The objective is the deterministic exact Observable of the evolved density matrix. A terminal Backend shot still completes each noisy Job lifecycle, but that count is not used as the objective. Readout acts only on final-sampling counts, so it cannot change the optimized energy, Problem penalty decomposition, or baseline gap.

Every evaluation and shift pair records its NoiseModel, requested options, selected SimulationPlan, NoiseReport, estimator, seed, Job, Result, standard errors, and Backend cost. Final sampling creates a separate Job with the same noise and options. Algorithm and Problem reports read those saved facts; generating a report never calls the Backend or optimizer again.

The exact-objective path remains density-matrix only. To use trajectory execution or make readout part of the energy estimate, pass PauliMeasurementConfig and use the sampled VQE path described above. Tensor-product readout mitigation is available only on that sampled VQE path; parameter-dependent noise, broader error mitigation, and Analog/Hybrid noisy optimization are not provided. compiled.decode(external_result) can decode a supplied result but does not invent Backend execution evidence.

Multiple Starts And Layer-Wise Initialization

Set starts to the total number of independent optimizer runs. Each start receives the full max_iterations and max_evaluations budget, so the total objective budget is at most starts * max_evaluations when that limit is set. A fixed seed reproduces every initial point and start seed.

p1 = QAOA(problem, layers=1).run(
    optimizer=OptimizerConfig(max_evaluations=8, seed=7),
)
p2 = QAOA(problem, layers=2).run(
    optimizer=OptimizerConfig(
        max_evaluations=12,
        starts=4,
        initialization="layerwise",
        seed=7,
    ),
    initial_parameters=p1.best_evaluation.parameter_bind.values,
)

Layer-wise QAOA requires exactly the canonical parameters from p-1 layers and interpolates each gamma/beta sequence to p layers. Both built-in VQE Definitions keep existing values and copy the corresponding previous-layer parameters into the new layer. ProblemCompiler.optimize_layers() and optimize_layers_repeated() perform that transfer before calling the optimizer. For a manual standalone VQE run, call transfer_vqe_parameters() first and pass the complete current-layer mapping; the optimizer deliberately does not infer layer structure from parameter names. Analog QAA and custom VQE circuits reject automatic layer transfer.

optimization_starts records every start's seed, initialization source, initial and final parameters, evaluation range, local best, and termination. evaluations remains the complete flattened Backend history, while selected_start_index identifies the start that owns best_evaluation.

Repeated Standalone VQE Layer Selection

Use VQE.optimize_layers_repeated() when a general Pauli Hamiltonian needs a reproducible depth experiment rather than one manually chosen layer count:

from cascaqit import OptimizerConfig, VQE

experiment = VQE(hamiltonian).optimize_layers_repeated(
    max_layers=4,
    repeats=3,
    optimizer=OptimizerConfig(method="COBYLA", max_evaluations=40),
    confidence_level=0.95,
    min_improvement=0.01,
    patience=2,
    final_shots=512,
    seed=7,
)

print(experiment.selected_layers)
print(experiment.selected_statistics.mean_objective)
experiment.report("vqe-repeated-layer.html", language="en")

Each repeat is a complete VariationalResult, including objective history, optimizer starts, final counts, noisy-execution evidence when requested, and fixed-cardinality evidence when that Ansatz is used. Repeat i at a deeper layer inherits only repeat i from the preceding layer. The result stores every run, per-layer mean and Student-t interval, paired improvements, the lower confidence bound used for selection, cumulative evaluation cost, and the stop reason.

For finite-shot depth selection, pass PauliMeasurementConfig, SampledSelectionConfig, and an SPSA or Adam optimizer to the same method. Both configs are required together. Every repeat first optimizes sampled Pauli energy, then independently confirms candidate points. Layer statistics use the selected candidate's pooled confirmation energy; the next layer inherits that candidate's parameters. The result and report separate objective or gradient Jobs/shots, confirmation Jobs/shots, and final computational-basis sampling.

The standard report combines all layer/repeat statistics with the complete lifecycle of the lowest layer-objective run at the selected layer. In sampled mode, that objective is the independent confirmation mean, not the minimum sampled value seen during optimization. The report reads the stored experiment and does not call the Backend or optimizer again.

The base optimizer must use seed=None, empty bounds, and random initialization because the experiment derives run seeds and manages changing parameter dimensions. At least two repeats are required. Only HardwareEfficientAnsatz and CardinalityPreservingAnsatz have a declared transferable layer structure; custom Circuits are rejected. The selected layer is supported only by the stored local runs under the supplied budgets and threshold. It is not a globally optimal depth or quantum-advantage claim.

Reading Results

Read best_evaluation for the minimum observed objective across all starts and its weighted Observable contributions. Read final_result for sampling counts. Problem inputs also provide most_probable_candidate, best_observed_candidate, decode facts, feasibility where defined, and a deterministic exhaustive baseline for at most 20 variables. These facts do not claim that the sampled candidate or optimizer result is globally optimal.

General Pauli VQE still performs final computational-basis sampling, but candidate decoding and a classical problem baseline are explicitly not applicable because no Problem semantics were supplied.

Run the complete small examples:

python3 examples/user/qaoa_mis_workflow.py
python3 examples/user/qaoa_qubo_workflow.py
python3 examples/user/vqe_ising_workflow.py
python3 examples/user/vqe_pauli_workflow.py
PYTHONPATH=src python3 examples/user/vqe_spsa_workflow.py \
  --output /tmp/cascaqit-vqe-spsa.html --language en
PYTHONPATH=src python3 examples/user/vqe_sampled_energy_workflow.py \
  --output-dir /tmp/cascaqit-vqe-sampled
PYTHONPATH=src python3 examples/user/vqe_sampled_spsa_workflow.py \
  --output /tmp/cascaqit-vqe-sampled-spsa.html --language en
PYTHONPATH=src python3 examples/user/vqe_readout_mitigation_workflow.py \
  --output-dir /tmp/cascaqit-vqe-readout-mitigation --language en
PYTHONPATH=src python3 examples/user/vqe_sampling_benchmark_workflow.py \
  --output /tmp/cascaqit-vqe-sampling-benchmark.html --language en
PYTHONPATH=src python3 examples/user/vqe_repeated_layer_workflow.py \
  --output /tmp/cascaqit-vqe-repeated-layer.html --language en
python3 examples/user/unified_vqe_ansatz_workflow.py
python3 examples/user/vqe_cardinality_workflow.py
python3 examples/user/variational_gradient_workflow.py --output-dir /tmp/cascaqit-gradient
python3 examples/user/noisy_variational_optimization.py --output-dir /tmp/cascaqit-noisy

For explicit ownership, import advanced contracts and projection helpers from cascaqit.algorithms. See Current Limitations before using the workflow for research benchmarks.

SDK 1.0.8a · `b3110f80`