HessianAutoscaler#
HessianAutoscaler scales the design variables using approximate eigenvalues and eigenvectors of the objective Hessian. It estimates this information once, at the initial design point, before optimization begins. For a quadratic objective, the Hessian is constant; for a nonlinear objective, its curvature can change during optimization.
The examples demonstrate how to apply the autoscaler and briefly show its potential. The first example compares SLSQP with and without Hessian-based scaling on a quadratic problem with linear equality constraints. A second example shows how design-variable bounds are handled.
HessianAutoscaler can be used with gradient-based optimizers. However, as shown in the second example, design-variable bounds are converted into linear inequality constraints, so the optimizer must support these constraints. For example, a bound-constrained problem solved using L-BFGS-B would require switching to an optimizer that supports general constraints, such as SLSQP or trust-constr in ScipyOptimizeDriver, or IPOPT or SNOPT in pyOptSparseDriver, when using HessianAutoscaler.
Because the Hessian-based transformation mixes the design variables, every constraint depends on every optimizer variable. Drivers therefore treat the total jacobian as dense when using HessianAutoscaler, rather than using the sparsity of the model.
Quadratic problem with equality constraints#
We solve
The Hessian is constructed as \(H = Q\Lambda Q^T\), where \(Q\) is orthogonal and \(\Lambda_{ii} = i^{-d}\) for \(i=1,\ldots,n\). Here, \(n=256\), \(d=1\), and \(b=0\). The unique solution is therefore \(x=0\), with \(f(x)=0\).
The component below evaluates the objective, the constraint residuals \(c(x)=Ax-b\), and their derivatives with respect to the design vector. The matrices and right-hand side are fixed problem data. We use a fixed random seed and the same initial point for both optimization runs.
import openmdao.api as om
import numpy as np
np.random.seed(42)
n_vars = 256 # number of design variables
n_cons = n_vars//2 # number of constraints
decay_rate = 1.0 # eigenvalue decay rate
x0 = np.random.randn(n_vars,1)
# Objective function parameters
Q, _ = np.linalg.qr(np.random.normal(loc=0, scale=1, size=(n_vars, n_vars)))
Lambda = 1.0 / np.arange(1, n_vars + 1, dtype=float)**decay_rate
# Constraints parameters
A = np.random.normal(loc=0, scale=1, size=(n_cons, n_vars))
b = np.zeros(n_cons)
# the objective Hessian matrix
H = Q @ np.diag(Lambda) @ np.transpose(Q)
class QuadraticProblem(om.ExplicitComponent):
"""Evaluate a quadratic objective and linear constraint residuals."""
def initialize(self):
self.options.declare('n_vars', types=int)
self.options.declare('n_cons', types=int)
def setup(self):
n_vars = self.options['n_vars']
n_cons = self.options['n_cons']
self.add_input('x', shape=(n_vars,))
self.add_input('H', shape=(n_vars,n_vars), desc="objective Hessian matrix")
self.add_input('A', shape=(n_cons,n_vars), desc="constraint Jacobian matrix")
self.add_input('b', shape=(n_cons,), desc="constraint vector")
self.add_output('c', shape=(n_cons,), desc="constraint residuals")
self.add_output('fx')
def setup_partials(self):
self.declare_partials('fx', 'x')
self.declare_partials('c', 'x')
def compute(self, inputs, outputs):
x = inputs['x']
H = inputs['H']
A = inputs['A']
b = inputs['b']
outputs['fx'] = 0.5 * x.T @ H @ x
outputs['c'] = A @ x - b
def compute_partials(self, inputs, partials):
partials['fx', 'x'] = (inputs['H'] @ inputs['x']).reshape(1, -1)
partials['c', 'x'] = inputs['A']
The baseline run script with no scaling#
The following can be used to run the optimization without any scaling, using the SLSQP optimizer:
prob = om.Problem(reports=False)
prob.model.add_subsystem('quad_obj', QuadraticProblem(n_vars=n_vars, n_cons=n_cons), promotes=['*'])
prob.driver = om.ScipyOptimizeDriver(optimizer='SLSQP', tol=1e-8, disp=True)
prob.driver.options['maxiter'] = 300
prob.model.add_design_var('x')
prob.model.add_objective('fx')
prob.model.add_constraint('c', equals=0.0)
prob.setup()
prob.set_val('x', x0.copy())
prob.set_val('A', A)
prob.set_val('b', b)
prob.set_val('H', H)
prob.run_driver()
print('f(x) = ', prob.get_val('fx'))
print('||x|| = ', np.linalg.norm(prob.get_val('x')))
print('||Ax - b|| = ', np.linalg.norm(prob.get_val('c')))
Optimization terminated successfully (Exit mode 0)
Current function value: 1.2432760707706028e-07
Iterations: 82
Function evaluations: 83
Gradient evaluations: 82
Optimization Complete
-----------------------------------
f(x) = [1.24327607e-07]
||x|| = 0.005691933971449958
||Ax - b|| = 2.0437264873802465e-17
Optimization terminated successfully (Exit mode 0)
Current function value: 1.2489326838270796e-07
Iterations: 84
Function evaluations: 85
Gradient evaluations: 84
Optimization Complete
-----------------------------------
f(x) = [1.24893268e-07]
||x|| = 0.005544603082868548
||Ax - b|| = 2.4088952727249008e-17
Applying the HessianAutoscaler#
Import the HessianAutoscaler class from openmdao.api, then assign an instance to prob.driver.autoscaler before calling setup().
from openmdao.api import HessianAutoscaler
When instantiating the HessianAutoscaler, all arguments are optional. The constructor accepts the following arguments:
Argument |
Meaning |
Default |
|---|---|---|
|
Number of retained/used Hessian eigenpairs. |
|
|
Number of Krylov iterations for the local Arnoldi implementation; number of Arnoldi vectors ( |
|
|
Finite difference step for approximating Hessian-vector products from objective gradients. |
|
|
Select SciPy’s |
|
|
Starting vector for eigenpair estimation, with the same size as the number of design variables. |
Pseudorandom vector from a fixed seed when |
The number of retained modes cannot exceed the number of design variables. SciPy’s eigs backend additionally requires num_modes < n_vars - 1 for the matrix-free operator used here. This example uses 16 of 256 modes, the local implementation and 32 Krylov iterations.
Objectives and constraints are scaled using their ref, ref0, scaler, and adder, as they are without the HessianAutoscaler, so a negative scaler or ref on the objective still maximizes it. Design variable ref, ref0, scaler, and adder are replaced by the Hessian-based scaling.
prob = om.Problem(reports=False)
prob.model.add_subsystem('quad_obj', QuadraticProblem(n_vars=n_vars, n_cons=n_cons), promotes=['*'])
prob.driver = om.ScipyOptimizeDriver(optimizer='SLSQP', tol=1e-8, disp=True)
prob.model.add_design_var('x')
prob.model.add_objective('fx')
prob.model.add_constraint('c', equals=0.0)
prob.driver.autoscaler = HessianAutoscaler(
num_modes=16,
num_krylov=32,
grad_fd_step=1e-6,
use_scipy_eigs=False,
start_vec=np.random.rand(n_vars)
)
prob.setup()
prob.set_val('x', x0.copy())
prob.set_val('A', A)
prob.set_val('b', b)
prob.set_val('H', H)
prob.run_driver()
print('f(x) = ', prob.get_val('fx'))
print('||x|| = ', np.linalg.norm(prob.get_val('x')))
print('||Ax - b|| = ', np.linalg.norm(prob.get_val('c')))
Optimization terminated successfully (Exit mode 0)
Current function value: 9.800308532097707e-09
Iterations: 25
Function evaluations: 25
Gradient evaluations: 25
Optimization Complete
-----------------------------------
f(x) = [9.80030853e-09]
||x|| = 0.00153324505464539
||Ax - b|| = 1.1535716550773889e-17
Optimization terminated successfully (Exit mode 0)
Current function value: 9.80030859069809e-09
Iterations: 25
Function evaluations: 25
Gradient evaluations: 25
Optimization Complete
-----------------------------------
f(x) = [9.80030859e-09]
||x|| = 0.0015332450594031447
||Ax - b|| = 1.2387914277951112e-17
Compare the optimizer summaries above to assess the impact of scaling with the HessianAutoscaler on this example. To see more benefits, we can make the problem more poorly-scaled by increasing decay_rate to 2.0 or 3.0; we can also double or quadruple n_vars to 512 or 1024.
We can also see more benefit by increasing num_modes. However, this would also increase the cost of estimating the eigenpairs. Eigenpair estimation requires additional gradient evaluations before optimization, so the optimizer’s iteration count alone does not measure the total computational cost. The missing piece is the gradient evaluations performed during the Arnoldi iteration to compute these eigenpairs, which are determined by the chosen num_krylov. Note that num_krylov >= num_modes. The number of gradient evaluations during the Arnoldi iteration can be extracted as:
print('Arnoldi gradient evaluations = ', prob.driver.autoscaler.arnoldi_grad_evals)
Arnoldi gradient evaluations = 34
Arnoldi gradient evaluations = 34
Both baseline and scaled runs should approach the same optimum. However, at a fixed stopping tolerance, scaling can reduce the iteration count and final numerical error; it does not change the mathematical solution or guarantee improved performance for every problem.
For problems with objectives that are nonlinear beyond quadratic, the Hessian is not constant; the curvature can change during optimization. Therefore, the autoscaler constructed based on the initial design might not be well-suited after several iterations. A user of the HessianAutoscaler could still benefit by restarting the optimization with the new design variables.
Handling design-variable bounds#
A matrix transformation can mix design variables, so bounds on model variables generally cannot be represented as independent bounds on optimizer variables. For \(x=My\), the bounds \(x_l\leq x\leq x_u\) become linear inequalities \(x_l\leq My\leq x_u\).
HessianAutoscaler performs this conversion automatically. During setup, each bounded design variable gets an equivalent linear constraint named <design var name>_bounds in the driver, using the design variable’s units and scaling, and the direct bounds are removed from the driver. The model itself is not modified, so add_design_var calls do not need to change and switching to a different autoscaler restores the ordinary bounds. The optimizer must support linear inequality constraints; otherwise an error is raised.
transform_desvar_bounds(prob) is still available if you want the conversion to be part of the model, for example to inspect the constraints with prob.model.get_constraints(). Call it after prob.setup() and before run_model(), final_setup(), or run_driver().
The example below keeps the bounds on the design variable.
prob = om.Problem(reports=False)
prob.model.add_subsystem('quad_obj', QuadraticProblem(n_vars=n_vars, n_cons=n_cons), promotes=['*'])
prob.driver = om.ScipyOptimizeDriver(optimizer='SLSQP', tol=1e-8, disp=True)
prob.model.add_design_var('x', lower=-1.0, upper=2.0)
prob.model.add_objective('fx')
prob.model.add_constraint('c', equals=0.0)
prob.driver.autoscaler = HessianAutoscaler(
num_modes=16,
num_krylov=32,
grad_fd_step=1e-6,
use_scipy_eigs=False,
start_vec=np.random.rand(n_vars),
)
prob.setup()
prob.set_val('x', x0.copy())
prob.set_val('A', A)
prob.set_val('b', b)
prob.set_val('H', H)
prob.run_driver()
print('f(x) = ', prob.get_val('fx'))
print('||x|| = ', np.linalg.norm(prob.get_val('x')))
print('||Ax - b|| = ', np.linalg.norm(prob.get_val('c')))
Optimization terminated successfully (Exit mode 0)
Current function value: 9.925396209195554e-09
Iterations: 25
Function evaluations: 25
Gradient evaluations: 25
Optimization Complete
-----------------------------------
f(x) = [9.92539621e-09]
||x|| = 0.001540381604926829
||Ax - b|| = 1.2081925939305361e-17
To learn more about the HessianAutoscaler, please see the published paper.