CustomVQA

class CustomVQA(qscript, *, param_shape=None, data_param_indices=None, feature_batch=None, arg_shapes=None, data_arg=None, labels=None, loss_fn='squared_error', loss_reduction='mean', max_iterations=10, **kwargs)[source]

Bases: DataBindingMixin, VariationalQuantumAlgorithm

Custom variational algorithm for a parameterized circuit.

Wraps a PennyLane QuantumScript, a PennyLane QNode, or a Qiskit QuantumCircuit and optimizes its trainable parameters to minimize a single expectation-value measurement. A QNode is converted to a QuantumScript upfront, with its required (no-default) arguments taken as the trainable parameters. Qiskit measurements on selected qubits convert to a sum-of-Z observable on those wires. Qiskit ParameterExpression objects (e.g. 2 * theta) are preserved natively through the Qiskit DAG.

Optionally accepts a classical feature_batch plus data_param_indices (indices into the circuit’s parameter ordering) to train in QNN style: the selected parameters are bound from each row of the batch via DataBindingStage, per-sample expectation values are aggregated by loss_reduction, and only the remaining parameters are exposed to the optimizer.

Variables:
  • qscript – The input QuantumScript or QuantumCircuit.

  • param_shape – Shape of a single parameter set.

  • n_qubits (int) – Number of qubits in the circuit.

  • n_layers (int) – Layer count (fixed to 1 for this wrapper).

  • cost_hamiltonian – Observable being minimized, as a Qiskit SparsePauliOp.

  • loss_constant (float) – Constant term extracted from the observable.

  • measured_wires (tuple[int, ...]) – For Qiskit input, the qubit indices targeted by measure instructions.

  • feature_batch (numpy.ndarray or None) – Classical feature batch when data binding is active; otherwise None.

  • labels (numpy.ndarray or None) – Supervised targets of shape (n_samples,) when training a supervised loss; otherwise None.

  • loss_reduction – User-facing aggregation across samples when data binding is active; ignored otherwise.

  • optimizer – Classical optimizer for parameter updates.

  • max_iterations (int) – Maximum number of optimization iterations.

  • current_iteration (int) – Current optimization iteration.

Initialize a CustomVQA instance.

Parameters:
  • qscript (QuantumScript | QNode | QuantumCircuit) – A parameterized QuantumScript or QNode with a single expectation-value measurement, or a Qiskit QuantumCircuit with computational-basis measurements (mapped to a sum-of-Z observable on the measured wires). QNode inputs are converted to QuantumScript upfront; the stored qscript attribute then holds the converted QuantumScript, not the original QNode. A QNode argument with a Python default is treated as a fixed constant (not trained), matching PennyLane’s trainability semantics. Structural values (qubit/layer counts used only for control flow, never as gate angles) are neither data nor weights: close over them in the enclosing scope or give them a default — a no-default structural argument is symbolized like a weight and then breaks (e.g. range(<symbol>)). The QNode is traced one sample at a time, so index by the structural size (range(n_qubits)), not the batch dimension (len(inputs[0])).

  • param_shape (tuple[int, ...] | int | None) – Shape of a single parameter set. If None, uses a flat shape inferred from trainable parameters. Must be None when data_param_indices is set — the optimizer view is automatically flat over the remaining weight parameters.

  • data_param_indices (Sequence[int] | None) – Integer indices (into the circuit’s flat parameter ordering) marking which parameters are bound from feature_batch rather than optimized. For Qiskit input, indices reference list(qc.parameters); for PennyLane input, indices reference the trainable-parameter ordering used to synthesize the internal parameter vector. Mutually required with feature_batch.

  • feature_batch (TypeAliasType | None) – Classical feature batch of shape (n_samples, len(data_param_indices)). Mutually required with data_param_indices (or data_arg).

  • arg_shapes (Mapping[str, tuple[int, ...]] | None) – For multi-argument or structured-shape QNode inputs (e.g. circuit(inputs, weights) with StronglyEntanglingLayers), maps each array argument’s name to its shape so the QNode can be traced symbolically. The data_arg’s shape is filled in automatically from feature_batch. Only valid for QNode inputs.

  • data_arg (str | None) – Name of the QNode argument fed from feature_batch (the data axis), as an alternative to data_param_indices for multi-argument QNodes. The remaining arguments’ parameters are the trainable weights. Requires feature_batch and a QNode input; mutually exclusive with data_param_indices.

  • labels (TypeAliasType | None) – Optional supervised targets of shape (n_samples,), aligned with feature_batch’s rows. When given (data binding must be active), each sample’s prediction (the observable’s expectation value) is compared to its label via loss_fn before loss_reduction aggregates — turning the unsupervised objective into a supervised training loss. None (default) keeps the unsupervised behavior.

  • loss_fn (Literal['squared_error'] | Callable[[float, float], float]) – Per-sample supervised loss (prediction, label) -> float, used only when labels is given. "squared_error" (default) with the default "mean" reduction yields mean-squared error; pass a callable for a custom loss. A custom callable must return a finite value — a NaN/Inf loss propagates to the optimizer with no diagnostic.

  • loss_reduction (Literal['mean', 'sum'] | Callable[[ndarray[tuple[Any, ...], dtype[double]]], float]) – How to aggregate the per-sample values (expectation values when unsupervised, or per-sample losses when labels is set) into the scalar loss the optimizer sees. "mean" (default), "sum", or a callable (n_samples,) -> float. Ignored when data_param_indices is unset.

  • max_iterations (int) – Maximum number of optimization iterations.

  • **kwargs – Additional keyword arguments passed to the parent class, including backend and optimizer.

Raises:
  • TypeError – If qscript is not a supported type.

  • ValueError – If the input has an invalid measurement, no trainable parameters, or inconsistent data-binding args.

Attributes Summary

n_params_per_layer

Number of trainable parameters per ansatz layer.

param_shape

Shape of a single parameter set.

Attributes Documentation

n_params_per_layer
param_shape

Shape of a single parameter set.