crabbymetrics
  • Home
  • API
    • API Overview
    • Regression And GLMs
    • Survival / Event-Time
    • Causal Inference And Panels
    • MPE_CBPS
    • Hypothesis Testing And Utilities
    • Transforms
    • Estimation Interfaces
  • Internals
  • Regression
    • OLS
    • ABC OLS
    • Anytime-Valid Confidence Sequences
    • Ridge
    • Bagged Polynomial Regression
    • Fixed Effects OLS
    • ElasticNet
    • Logit
    • Multinomial Logit
    • Poisson
    • MLE Prediction Interface
    • Survival / Recurrent Events
    • GMM
    • MEstimator Poisson
  • Causal / Panels
    • Balancing Weights
    • Chronos LTV Balancing
    • Cressie-Read And Rényi Balancing
    • EPLM
    • Average Derivative
    • Double ML And AIPW
    • Richer Regression
    • TwoSLS
    • FE Counterfactual Imputation
    • Synthetic Control
    • Synthetic DID
    • Augmented Balancing For Panel Data
    • Horizontal Panel Ridge
    • Matrix Completion
    • Interactive Fixed Effects
    • Staggered Panel Event Study
    • Joint Hypothesis Tests
    • Dynamic Treatment Effects
  • Transforms
    • PCA And Kernel Basis
    • Sparse Factor Rotations
  • Ablations
    • Variance Estimators
    • Semiparametric Estimator Comparisons
    • Two-Period Semiparametric DID
    • Bridging Finite And Superpopulation
    • Lecture-Motivated Panel Fixes
    • Panel Estimator DGP Comparisons
    • Same Root Panel Case Studies
    • Randomized Sketching And Least Squares
    • Estimator Scaling And References
  • Optimization
    • Optimizer Robustness And Timings
    • Optimizers
    • GMM With Optimizers
  • Ding
    • Chapter Index
    • Foundations (1-4)
    • Design And Adjustment (5-8)
    • Finite And Superpopulation (9)
    • Observational Studies (11-13, 27)
    • Instrumental Variables (21, 23)

On this page

  • 1 Where it fits
  • 2 Solver mechanics
    • 2.1 BFGS and L-BFGS
    • 2.2 Dense exact-Hessian trust regions
    • 2.3 BHHH likelihood-score curvature
    • 2.4 Scaling and certified results
    • 2.5 Nonlinear conjugate gradient
    • 2.6 Gauss-Newton least squares
    • 2.7 Simulated annealing
  • 3 Performance and failure behavior
  • 4 Python API
  • 5 Minimal example
  • 6 summary() contract

Optimizers

Static optimization routines for Python callbacks

The trust-region/BHHH additions and revised BFGS/L-BFGS controls described here are unreleased development APIs. Build the proposed source branch to use them.

1 Where it fits

Group: Estimation interfaces

Optimizers is a small namespace for callback-driven numerical optimization. It is not an estimator; it exposes reusable routines for smooth objectives, nonlinear least squares, and a simple stochastic global search.

2 Solver mechanics

All methods bridge Python callbacks into Rust and normalize the result into the same dictionary, but their step construction and success rules differ.

2.1 BFGS and L-BFGS

Both call fun(theta) and grad(theta) in original coordinates. The package now owns the generic optimizer loops, including strong-Wolfe bracketing/bisection zoom, rejection of nonfinite trials, curvature-update checks and non-descent resets. BFGS stores a dense inverse approximation initialized at identity; L-BFGS retains seven correction pairs. Native estimator classes retain their existing solvers.

The old positional signature is retained. gtol overrides the legacy gradient tolerance; independent relative cost-stagnation ftol defaults to zero (off). A cost stop, line-search failure or exhausted budget cannot itself report success: the returned point is independently gradient-checked. c1, c2 and max_linesearch expose step controls. Invalid initial arrays and Python callback exceptions raise; numerical nonfiniteness at a trial is rejected.

2.2 Dense exact-Hessian trust regions

minimize_trust_region(fun, x0, grad, hess, ...) minimizes a quadratic model inside a Euclidean ball. hess(theta) returns a finite symmetric float64 matrix of shape (p, p). A dense spectral subproblem solve uses a safeguarded curvature shift, including singular/interior solutions and the hard case with negative curvature orthogonal to the gradient. Actual/predicted reduction controls the radius and acceptance. A small gradient with detected negative curvature is not successful termination. This native Rust method is intended for modest parameter dimensions and is not a GALAHAD binding.

2.3 BHHH likelihood-score curvature

minimize_bhhh(fun, x0, scores, ...) uses rows of negative-log-likelihood gradients, not positive log-likelihood scores. For reduction="mean" (default), the gradient and curvature are the mean row score and mean outer product; reduction="sum" uses sums. fun must use the same normalization.

Instead of materializing an observation-by-parameter matrix, pass score_stats=callback with scores=None. This callback returns (score_sum, outer_sum, n_observations) accumulated over batches, before the selected reduction. The two callback interfaces are mutually exclusive. penalty_grad and penalty_hess are optional paired callbacks: their derivatives are added once, after likelihood normalization, and the penalty belongs in fun. They must not already be included in the row scores.

BHHH applies a positive spectral curvature floor controlled by damping and a strong-Wolfe line search. Its information-identity motivation is local and model-specific. It is not a generic GMM solver, an inference procedure or a guarantee of good curvature at a distant start.

2.4 Scaling and certified results

For all four methods above, optional positive x_scale defines x=\operatorname{diag}(\texttt{x\_scale})z. Callbacks receive original x. optimality is \|\nabla_z f\|_\infty, while jac and grad_norm describe original-coordinate gradients. The final certificate is optimality <= gtol; trust regions additionally reject detectable final negative curvature.

The original dictionary keys remain. New diagnostics include status, jac, optimality, grad_norm, nfev, njev, nhev, nscorev, rejected_steps, resets and skipped_updates. Counters include final checking evaluations; nscorev counts actual score callbacks, while njev counts gradient requests. Trust regions also report the final radius and scaled min_eigenvalue. Numerical curvature and damping are not returned as statistical covariance.

2.5 Nonlinear conjugate gradient

This method uses Polak-Ribiere-plus directions and an Armijo backtracking line search with sufficient-decrease constant 0.2. It supports periodic and orthogonality restarts. Because the underlying solver does not use the public tolerance directly, the wrapper reevaluates the final Python gradient and upgrades the result to success when its Euclidean norm is at most tolerance.

2.6 Gauss-Newton least squares

The package owns this loop. At each iterate it calls the residual and Jacobian functions, requires Jacobian shape (n_residuals, n_parameters), forms g=J'r and J'J, explicitly inverts J'J, and proposes (J'J)^{-1}g. Gradient or step norm below tolerance stops. Otherwise a halving line search requires strict decrease in \|r\|^2/2 down to scale 10^{-8}. A small objective change succeeds; a singular normal matrix, callback error, or malformed shape raises, while line-search or iteration exhaustion returns success=False.

2.7 Simulated annealing

The proposal modifies at least one randomly selected coordinate, adds a uniform perturbation in [-step_size, step_size], and clamps it to optional elementwise bounds. Proposal and acceptance RNGs use separate Xoshiro streams; with a seed the second stream uses seed + 1. Argmin’s Boltzmann temperature schedule runs until its stopping status or 1,000 consecutive stalls in best or accepted states. This is the only method that can use OS entropy when no seed is supplied.

3 Performance and failure behavior

Every objective, gradient, residual or Jacobian callback crosses the Python-Rust boundary. BFGS and dense trust regions store O(p^2) numerical state, L-BFGS keeps O(p) state for a fixed history, and BHHH forms an O(p^2) score cross-product. Row-score callbacks may materialize O(np) input; score_stats supports bounded batches. Dense spectral solves cost O(p^3). Callbacks should be deterministic and consistently normalized.

The executed stress comparison reports six estimator families, accuracy, fresh timings and convergence paths.

4 Python API

Constructor: cm.Optimizers

The methods are static and return plain dictionaries with scipy-like keys: x, fun, nit, success, message, and method. Smooth minimizers require objective and gradient callbacks; Gauss-Newton requires residual and Jacobian callbacks; simulated annealing only requires the objective.

Code
print(inspect.signature(cm.Optimizers))
()
Code
cls = cm.Optimizers
display(HTML(html_table(["Public method"], public_methods(cls))))
Public method
Optimizers()
minimize_bfgs(fun, x0, grad, max_iterations=100, tolerance=1e-06, *, gtol=None, ftol=0.0, c1=0.0001, c2=0.9, max_linesearch=80, x_scale=None)
minimize_bhhh(fun, x0, scores=None, max_iterations=100, tolerance=1e-06, *, score_stats=None, reduction='mean', penalty_grad=None, penalty_hess=None, gtol=None, ftol=0.0, damping=1e-08, c1=0.0001, c2=0.9, max_linesearch=80, x_scale=None)
minimize_gauss_newton_ls(residual_fn, x0, jacobian_fn, max_iterations=100, tolerance=1e-06)
minimize_lbfgs(fun, x0, grad, max_iterations=100, tolerance=1e-06, *, gtol=None, ftol=0.0, c1=0.0001, c2=0.9, max_linesearch=80, x_scale=None)
minimize_nonlinear_cg(fun, x0, grad, max_iterations=100, restart_iters=10, restart_orthogonality=0.1, tolerance=1e-06)
minimize_simulated_annealing(fun, x0, lower=None, upper=None, temp=15.0, step_size=0.1, max_iterations=5000, seed=None)
minimize_trust_region(fun, x0, grad, hess, max_iterations=100, tolerance=1e-06, *, gtol=None, ftol=0.0, initial_radius=1.0, max_radius=1000000.0, eta=0.1, x_scale=None)

5 Minimal example

def fun(theta):
    return float(np.sum((theta - np.array([1.0, -2.0])) ** 2))
def grad(theta):
    return 2.0 * (theta - np.array([1.0, -2.0]))
res = cm.Optimizers.minimize_bfgs(fun, np.zeros(2), grad, max_iterations=100)
print(res)
{'x': array([ 1., -2.]), 'fun': 0.0, 'jac': array([0., 0.]), 'optimality': 0.0, 'grad_norm': 0.0, 'nit': 1, 'success': True, 'status': 'gradient_tolerance', 'message': 'Final gradient satisfies gtol', 'method': 'bfgs', 'nfev': 4, 'njev': 4, 'nhev': 0, 'nscorev': 0, 'rejected_steps': 1, 'resets': 0, 'skipped_updates': 0}

6 summary() contract

The table below is generated by fitting the live class in this repository and then inspecting summary(). Shapes are shown because most values are plain NumPy arrays or scalars.

Code
class _Dummy:

    def summary(self):
        return {'note': 'Optimizers has static methods, not fitted state'}
model = _Dummy()
summary = model.summary()
display(HTML(html_table(["summary() key", "shape"], summary_shape_rows(summary))))
summary() key shape
note ()

crabbymetrics 0.9.1

 
  • v0.9.1 release

  • v0.9 migration

  • Reproduction