Method-specific solvers

The algorithms behind the high-level interfaces, with every setting exposed. least_squares() runs gauss_newton() and passes its other keyword arguments through. minimize() runs lbfgs() by default and passes its options to it (with a torch.optim.Optimizer class as method, it runs that optimiser instead). Call these directly when you build the normal equations yourself (for example a sparse J^T J), or to use one method without going through the interface.

piazzi.gauss_newton(system, x0, *, method='lm', has_aux=False, manifold=None, value_fun=None, max_iter=100, max_step=1.0, step_tol=1e-05, c1=0.0001, max_backtracks=10, gn_ridge=1e-06, tau=0.001, max_rejections=6, damping='identity', solve_dtype=torch.float64, solve_device='cpu', linear_solver=None, callback=None, verbose=False)[source]

Gauss-Newton or Levenberg-Marquardt on user-supplied normal equations.

Minimises a loss given its gradient g and a curvature model H (usually J^T W J) at each point. Only the (n, n) system is moved to solve_device and solved in solve_dtype: float64 on the CPU by default, which avoids float32 trouble and is cheap when n is small. Steps are capped so that no coordinate moves more than max_step.

  • method="lm" (Levenberg-Marquardt): step -(H + lam D)^{-1} g, with lam initialised from tau and updated from the gain ratio (actual / predicted decrease) by Nielsen’s rule. After an accepted step the next trial evaluates the full system (it is usually accepted too); after a rejection the trial is value-only.

  • method="gn" (Gauss-Newton): step -(H + ridge D)^{-1} g, then Armijo backtracking (halving) with value-only evaluations. If H is indefinite, or a custom linear_solver returns an uphill step, the iteration falls back to steepest descent.

D is the identity, or diag(H) with damping="marquardt".

The run stops, as converged, once a step is below step_tol (max-norm), when the gradient is exactly zero (a stationary point, where H may be singular), or when a step fails but the model predicted a decrease below the rounding noise of the loss, 8 * eps * |loss| in the loss’s dtype (for Levenberg-Marquardt, the prediction of the first trial from the current point). That last test ends a float32 objective at its minimiser, where rounding noise in the gradient keeps steps above step_tol; it plays the role of Ceres Solver’s function_tolerance. Near a zero residual the loss’s rounding noise is absolute and that test cannot see it, so a failed step also counts as converged when the Gauss-Newton step, which estimates the distance to the minimiser, leaves x unmoved: every entry within 64 units in the last place of its scale (|x|, or the manifold’s entry_scale()). The loss cannot change measurably along such a step. For Levenberg-Marquardt, whose first trial from a point is damped, the undamped Gauss-Newton step is checked as well (one extra linear solve), and a trial with a non-finite value never counts. A trial point with a non-finite value is never accepted, and a non-finite value at x0 stops the run at once.

H may be a sparse COO or CSR tensor, for problems with many parameters but few nonzeros in J^T J (bundle adjustment, for example). The solver then only needs its diagonal and matrix-vector products.

Parameters:
  • system (Callable) – system(x) -> (loss, g, H), or (loss, g, H, aux) with has_aux=True. loss is a scalar tensor, g its gradient of shape (n,) and H a positive semi-definite curvature model of shape (n, n), dense or sparse. x has the shape of x0. Called without gradient tracking. piazzi.least_squares_system() builds one from residuals.

  • x0 (torch.Tensor) – starting point, of any shape. n is its number of elements, or the tangent size of manifold.

Keyword Arguments:
  • method (str, optional) – "lm" (Levenberg-Marquardt) or "gn" (Gauss-Newton). Default: "lm"

  • has_aux (bool, optional) – whether system also returns an auxiliary output (any tree of tensors), returned detached in result.aux and info.aux. Default: False

  • manifold (piazzi.Manifold, optional) – keeps x on a manifold such as piazzi.SE3. g and H are then in tangent coordinates at x (piazzi.least_squares_system() builds them that way when given the same manifold), each step is applied as x <- manifold.plus(x, step), and max_step and step_tol apply to the tangent step. Default: None

  • value_fun (Callable, optional) – a cheaper value_fun(x) -> loss (or (loss, aux)) for value-only evaluations. Default: None, which uses the loss that system returns.

  • max_iter (int, optional) – maximum number of iterations, accepted or rejected. Default: 100

  • max_step (float, optional) – largest change of any coordinate in one step (in the units of x, or of the tangent vector). Default: 1.0

  • step_tol (float, optional) – stop, as converged, once an accepted step’s max-norm is below this. The step must estimate the distance to the minimiser: the full Gauss-Newton step before any backtracking, and for Levenberg-Marquardt, when the damped step is that short, also the undamped Gauss-Newton step. A step shortened by backtracking or damping alone does not count, and a step that does not change x at all is never accepted. Default: 1e-5

  • c1 (float, optional) – Armijo sufficient-decrease constant (method="gn"). Default: 1e-4

  • max_backtracks (int, optional) – maximum number of step halvings in one line search (method="gn"). Default: 10

  • gn_ridge (float, optional) – ridge added to H for method="gn", relative to mean(diag H) (or to D with damping="marquardt"). Default: 1e-6

  • tau (float, optional) – initial Levenberg-Marquardt damping, relative to max(diag H) (or to D with damping="marquardt"). Default: 1e-3

  • max_rejections (int, optional) – stop after this many rejected Levenberg-Marquardt steps in a row. Default: 6

  • damping (str, optional) – "identity" (D = I) or "marquardt" (D = diag(H), floored at 1e-12 * max(diag H), as in Ceres Solver). The Marquardt damping scales with each parameter’s curvature, which helps when parameters have very different units; it plays the role of x_scale="jac" in scipy.optimize.least_squares(). Default: "identity"

  • solve_dtype (torch.dtype, optional) – dtype of the linear solve. Default: torch.float64

  • solve_device (str or torch.device, optional) – device of the linear solve. Default: "cpu"

  • linear_solver (piazzi.LinearSolver, optional) – solver(H, g, damping) -> d solving (H + diag(damping)) d = -g (see piazzi.LinearSolver). Default: None, which uses piazzi.dense_solver() for a dense H and piazzi.cg_solver() (Jacobi-preconditioned conjugate gradients, which needs torchsparsegradutils) for a sparse one.

  • callback (Callable, optional) – called with an piazzi.IterationInfo after every iteration, accepted or not; returning True stops the run. Default: None

  • verbose (bool or int, optional) – print a table of the run’s progress with piazzi.print_progress() before calling callback: True prints every iteration and an integer k every k-th one. Default: False

Returns:

OptimizeResult – the solution x (shaped like x0), the final loss fun and aux, n_iter, the counts n_system (full system evaluations) and n_fun (value-only evaluations), and converged and message.

See also

Example:

>>> t = torch.linspace(0, 1, 20, dtype=torch.float64)
>>> y = 2 * torch.exp(-3 * t)
>>> system = piazzi.least_squares_system(lambda p: p[0] * torch.exp(-p[1] * t) - y)
>>> res = piazzi.gauss_newton(system, torch.tensor([1.0, 1.0], dtype=torch.float64))
>>> res.x
tensor([2.0000, 3.0000], dtype=torch.float64)
piazzi.levenberg_marquardt(system, x0, **kwargs)[source]

Levenberg-Marquardt: piazzi.gauss_newton() with method="lm".

Parameters:
Returns:

OptimizeResult – as for piazzi.gauss_newton().

See also

piazzi.lbfgs(fun, x0, *, has_aux=False, manifold=None, value_fun=None, max_iter=100, lr=1.0, history_size=10, line_search='armijo', c1=0.0001, c2=0.9, hz_epsilon=1e-06, max_backtracks=10, max_step=1.0, step_tol=1e-05, callback=None, verbose=False)[source]

Minimise a scalar function with L-BFGS and a line search.

Built for expensive, deterministic objectives, where every evaluation counts.

Armijo backtracking (line_search="armijo", the default): each iteration tries the full step (lr times the L-BFGS direction, scaled by min(1, 1 / ||g||_1) while there is no curvature history, at the start or after a reset), capped so that no coordinate moves more than max_step. If the sufficient-decrease condition (Armijo, parameter c1) fails, the step is shrunk by quadratic interpolation up to max_backtracks times. Each trial point is evaluated with its autograd graph kept, and the backward pass runs only once a point is accepted: a typical iteration costs one value-and-gradient evaluation, a rejected trial costs a forward pass only, and no point is evaluated twice.

Strong Wolfe (line_search="strong_wolfe"): a bracketing phase followed by a zoom phase with cubic interpolation, following Nocedal and Wright Algorithm 3.5/3.6 (ported from torch.optim.LBFGS). Every trial point requires a gradient evaluation (the curvature condition needs it), so rejected trials cost one n_fun_grad count instead of one n_fun count. value_fun is ignored when line_search="strong_wolfe". A step that satisfies the curvature condition (parameter c2) has sᵀy > 0, so its curvature pair is kept; if the search ends on the Armijo condition alone (its trial budget is spent, or the step reached max_step), the pair is kept only if sᵀy > 0, as with Armijo. On a failed search the memory is still reset and the solver retries with steepest descent, exactly as with Armijo.

Hager-Zhang (line_search="hager_zhang"): the line search of CG_DESCENT (Hager and Zhang, 2006, ported from LineSearches.jl): bracketing, then secant steps and bisection, accepting a point that satisfies the Wolfe conditions (c1, c2) or the approximate Wolfe conditions, which compare slopes instead of values and so stay meaningful near a minimiser, where the loss differences drown in rounding noise (hz_epsilon bounds how far the loss may exceed its starting value for them to apply). Like strong Wolfe, every trial needs its gradient (n_fun_grad) and value_fun is ignored. Unlike it, a step satisfying the approximate conditions may raise the loss by up to hz_epsilon * |loss| (hz_epsilon=0 keeps the loss from rising), a non-finite trial shrinks the step instead of failing the search, and the interpolation is by secant steps on the slope, not cubic.

Convergence (every line search): curvature pairs with s·y ≤ 0 are skipped (the strong Wolfe curvature condition rules them out when it holds). If no sufficient decrease is found, the memory is reset and the iterate does not move; the run retries once with steepest descent. It stops after two failures in a row, after one failure of a steepest-descent step, or once a step is below step_tol (max-norm). The stop counts as convergence when the last failed search from the L-BFGS memory showed a minimiser to working precision: its step left x unmoved (every entry within 64 units in the last place of its scale, |x| or the manifold’s entry_scale(), at a finite value), or the loss did not measurably go up (by more than 8 * eps * |loss|) while that step was below step_tol or predicted a decrease below rounding noise. A trial point with a non-finite value never passes the line search, and a non-finite value at x0 stops the run at once.

Parameters:
  • fun (Callable) – fun(x) -> loss, or (loss, aux) with has_aux=True, where loss is a scalar tensor differentiable with respect to x and x has the shape of x0.

  • x0 (torch.Tensor) – starting point, of any shape (it is flattened internally).

Keyword Arguments:
  • has_aux (bool, optional) – whether fun also returns an auxiliary output (any tree of tensors), returned detached in result.aux and info.aux. Default: False

  • manifold (piazzi.Manifold, optional) – keeps x on a manifold such as piazzi.SE3. The gradient is then taken with respect to the tangent vector delta of fun(manifold.plus(x, delta)) at delta = 0, steps are applied with manifold.plus, and the curvature pairs are kept in tangent coordinates without vector transport (as in Ceres Solver’s line-search solver). max_step and step_tol apply to the tangent step. Default: None

  • value_fun (Callable, optional) – a cheaper value_fun(x) -> loss for the Armijo backtracking evaluations, run under torch.no_grad. The gradient at an accepted backtracked point then needs one more call to fun. With the default, the backtracking evaluates fun itself and records its graph for the deferred backward pass; if fun is much cheaper without a graph, pass value_fun=fun to backtrack under torch.no_grad instead. Ignored when line_search="strong_wolfe", which always needs the gradient. Default: None

  • max_iter (int, optional) – maximum number of iterations. Default: 100

  • lr (float, optional) – initial step length along the L-BFGS direction. Default: 1.0

  • history_size (int, optional) – number of curvature pairs kept. Default: 10

  • line_search (str, optional) – "armijo" for cheap Armijo backtracking (one forward pass per rejected trial), "strong_wolfe" for the bracketing and zoom method with cubic interpolation, or "hager_zhang" for the CG_DESCENT search (one value-and-gradient evaluation per trial for both). Default: "armijo"

  • c1 (float, optional) – sufficient-decrease (Armijo) constant, used by every line search; "hager_zhang" needs c1 < 1/2 (its delta). Default: 1e-4

  • c2 (float, optional) – curvature constant of the Wolfe conditions; must satisfy c1 < c2 < 1 (checked unless line_search="armijo", which ignores it). Default: 0.9

  • hz_epsilon (float, optional) – relative tolerance of the approximate Wolfe conditions of "hager_zhang": they apply to points whose loss is at most loss + hz_epsilon * |loss|, so a step may raise the loss by that much; 0 keeps every step monotone. Ignored by the other line searches. Default: 1e-6

  • max_backtracks (int, optional) – maximum number of trial points in one line search after the first one (step reductions for Armijo, bracketing and zoom trials for strong Wolfe, evaluations for Hager-Zhang), so a search makes at most max_backtracks + 1 evaluations. Default: 10

  • max_step (float, optional) – largest change of any coordinate in one step (in the units of x, or of the tangent vector). Default: 1.0

  • step_tol (float, optional) – stop, as converged, once an accepted step from the L-BFGS memory has a max-norm below this. A step shortened by backtracking counts only if the full step was below it too, or if the step made no measurable progress (at a minimiser the line search may accept a step that changes nothing), or if the full step barely moved x (1024 units in the last place of each entry’s scale), as at a float32 noise floor. Default: 1e-5

  • callback (Callable, optional) – called with an piazzi.IterationInfo after every iteration, accepted or not; returning True stops the run. Default: None

  • verbose (bool or int, optional) – print a table of the run’s progress with piazzi.print_progress() before calling callback: True prints every iteration and an integer k every k-th one. Default: False

Returns:

OptimizeResult – the solution x (shaped like x0), the final loss fun and aux, n_iter, the counts n_fun_grad (value and gradient) and n_fun (value only, Armijo backtracking only), and converged and message.

See also

  • piazzi.minimize(): the high-level interface, which runs this method by default and passes its options here.

Example:

>>> def rosenbrock(x):
...     return (100 * (x[1:] - x[:-1] ** 2) ** 2 + (1 - x[:-1]) ** 2).sum()
>>> res = piazzi.lbfgs(rosenbrock, torch.tensor([-1.2, 1.0], dtype=torch.float64))
>>> res.x, res.converged
(tensor([1.0000, 1.0000], dtype=torch.float64), True)
>>> res_sw = piazzi.lbfgs(
...     rosenbrock, torch.tensor([-1.2, 1.0], dtype=torch.float64),
...     line_search="strong_wolfe",
... )
>>> res_sw.x, res_sw.converged
(tensor([1.0000, 1.0000], dtype=torch.float64), True)
>>> res_hz = piazzi.lbfgs(
...     rosenbrock, torch.tensor([-1.2, 1.0], dtype=torch.float64),
...     line_search="hager_zhang",
... )
>>> res_hz.x, res_hz.converged
(tensor([1.0000, 1.0000], dtype=torch.float64), True)
piazzi.least_squares_system(residual_fun, has_aux=False, *, loss='linear', f_scale=1.0, curvature='irls', manifold=None)[source]

Build normal equations from residuals, for piazzi.gauss_newton().

The returned system(x) gives (loss, g, H) for the cost F = 0.5 * sum(C^2 * rho(z)) with z = (r / C)^2 and C = f_scale, as in scipy.optimize.least_squares(). With the default loss="linear" this is F = 0.5 * ||r||^2, g = J^T r and H = J^T J. For a robust loss the gradient is g = J^T (rho'(z) * r) and H = J^T diag(w) J, with weights w set by curvature. The Jacobian J of shape (m, n) comes from forward-mode autodiff (torch.func.jacfwd()), which is cheap when there are few parameters. For large or structured problems, write system by hand and reduce J^T J without materialising J.

Parameters:
  • residual_fun (Callable) – residual_fun(x) -> r, or (r, aux) with has_aux=True, where r is a tensor of residuals of any shape (flattened to (m,)) and x has the shape of the point passed to system.

  • has_aux (bool, optional) – whether residual_fun also returns an auxiliary output (any tree of tensors), which system then returns as a fourth element. Default: False

Keyword Arguments:
  • loss (str or Callable, optional) – a name from piazzi.LOSSES ("linear", "huber", "soft_l1", "cauchy", "arctan"), or a callable rho(z) written in PyTorch and applied elementwise, whose derivatives come from autograd. Default: "linear"

  • f_scale (float, optional) – soft margin C between inlier and outlier residuals, in the units of r. Default: 1.0

  • curvature (str, optional) –

    the weights w of H = J^T diag(w) J for a robust loss. The gradient does not depend on it, so the choice changes the path, not the minimiser. Default: "irls"

    • "irls": w = rho'(z), as in iteratively reweighted least squares. Ceres Solver uses the same weights for losses with rho'' <= 0, which includes every built-in loss.

    • "scipy": w = max(rho'(z) + 2 * rho''(z) * z, eps), the model of scipy.optimize.least_squares(). It is more accurate for inliers, but for outliers the bracket is negative and floored at eps. When most residuals start as outliers, H is then nearly singular and Levenberg-Marquardt can stall; method="gn" copes better.

  • manifold (piazzi.Manifold, optional) – keeps x on a manifold. J is then the Jacobian of delta -> r(manifold.plus(x, delta)) at delta = 0, so g and H are in tangent coordinates (for example 6 columns for piazzi.SE3). Pass the same manifold to piazzi.gauss_newton(). Default: None

Returns:

Callable – system(x) -> (loss, g, H), or (loss, g, H, aux) with has_aux, with g of shape (n,) and H of shape (n, n).

See also