Optimizer

class Optimizer[source]

Bases: ABC

Abstract base class for all optimizers.

Warning

Thread Safety: Optimizer instances are not thread-safe. They maintain internal state (e.g., current population, iteration count, RNG state) that changes during optimization.

Do not share a single Optimizer instance across multiple QuantumProgram instances or threads running in parallel. Doing so will lead to race conditions, corrupted state, and potential crashes.

If you need to use the same optimizer configuration for multiple programs, create a separate instance for each program. You can call copy() to create a fresh copy with the same configuration.

Attributes Summary

n_param_sets

Returns the number of parameter sets the optimizer can handle per optimization run.

supports_checkpointing

Whether this optimizer can persist and restore its state mid-run.

Methods Summary

build_evaluators(program)

Extra per-run evaluators this optimizer needs from the program.

copy()

Return a fresh instance with the same configuration and no accumulated run state.

get_config()

Get optimizer configuration for checkpoint reconstruction.

load_state(checkpoint_dir)

Load the optimizer's internal state from a checkpoint directory.

optimize(cost_fn[, initial_params, callback_fn])

Optimize the given cost function starting from initial parameters.

reset()

Reset the optimizer's internal state to allow fresh optimization runs.

save_state(checkpoint_dir)

Save the optimizer's internal state to a checkpoint directory.

validate_program(program)

Check that this optimizer can be applied to program.

Attributes Documentation

n_param_sets

Returns the number of parameter sets the optimizer can handle per optimization run. :returns: Number of parameter sets. :rtype: int

supports_checkpointing

Whether this optimizer can persist and restore its state mid-run.

Programs guard on this before checkpointing so an optimizer that cannot save state fails upfront rather than mid-optimization. Optimizers whose save_state() raises NotImplementedError override this to return False.

Methods Documentation

build_evaluators(program)[source]

Extra per-run evaluators this optimizer needs from the program.

Called once by the variational algorithm before optimization. The returned mapping may override "jac" and/or add "metric_fn"; keys absent from the mapping fall back to the algorithm’s defaults. The base implementation needs nothing extra and returns {}.

Return type:

dict[str, Callable[[ndarray[tuple[Any, ...], dtype[double]]], Any]]

copy()[source]

Return a fresh instance with the same configuration and no accumulated run state.

The default deep-copies the optimizer, which is correct for the stateless optimizers whose only attributes are configuration; optimizers that accumulate per-run state override this to rebuild from configuration alone.

Tip

Use this when preparing a batch of programs that will run in parallel. Optimizer instances are not thread-safe (see the class warning); give each program its own optimizer.copy() to avoid state contamination.

Return type:

Optimizer

abstractmethod get_config()[source]

Get optimizer configuration for checkpoint reconstruction.

Returns:

Dictionary containing optimizer type and configuration parameters.

Return type:

dict[str, Any]

Raises:

NotImplementedError – If the optimizer does not support checkpointing.

abstractmethod classmethod load_state(checkpoint_dir)[source]

Load the optimizer’s internal state from a checkpoint directory.

Creates a new optimizer instance with the state restored from the checkpoint.

Parameters:

checkpoint_dir (Path | str) – Directory path where the optimizer state is saved.

Returns:

A new optimizer instance with restored state.

Return type:

Optimizer

abstractmethod optimize(cost_fn, initial_params=None, callback_fn=None, **kwargs)[source]

Optimize the given cost function starting from initial parameters.

Parameters:
  • cost_fn (Callable[[ndarray[tuple[Any, ...], dtype[double]]], float | ndarray[tuple[Any, ...], dtype[double]]]) – The cost function to minimize.

  • initial_params (ndarray[tuple[Any, ...], dtype[double]] | None) – Initial parameters for the optimization.

  • callback_fn (Callable[[OptimizeResult], Any] | None) – Function called after each iteration with an OptimizeResult object.

  • **kwargs

    Additional keyword arguments for the optimizer:

    • max_iterations (int, optional): Total desired number of iterations. When resuming from a checkpoint, this represents the total iterations desired across all runs. The optimizer will automatically calculate and run only the remaining iterations needed. Defaults vary by optimizer (e.g., 5 for population-based optimizers, None for some scipy methods).

    • rng (np.random.Generator, optional): Random number generator for stochastic optimizers (PymooOptimizer, MonteCarloOptimizer). Defaults to a new generator if not provided.

    • jac (Callable, optional): Gradient/Jacobian function for gradient-based optimizers (only used by ScipyOptimizer with L_BFGS_B method). Defaults to None.

Return type:

OptimizeResult

Returns:

OptimizeResult whose x is the single best parameter set as a 1-D array of shape (n_params,). (The per-iteration callback_fn receives a 2-D x of shape (n_param_sets, n_params); only the final result is 1-D.)

abstractmethod reset()[source]

Reset the optimizer’s internal state to allow fresh optimization runs.

Clears any state accumulated during previous optimization runs, allowing the optimizer to be reused for new optimization problems without creating a new instance.

Return type:

None

abstractmethod save_state(checkpoint_dir)[source]

Save the optimizer’s internal state to a checkpoint directory.

Parameters:

checkpoint_dir (Path | str) – Directory path where the optimizer state will be saved.

Return type:

None

validate_program(program)[source]

Check that this optimizer can be applied to program.

Called at the start of run(), before any optimization, so an incompatible optimizer/program pairing fails loudly and early. The base implementation accepts any program; override to raise when the optimizer’s requirements are not met.

Return type:

None