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
gand a curvature modelH(usuallyJ^T W J) at each point. Only the(n, n)system is moved tosolve_deviceand solved insolve_dtype: float64 on the CPU by default, which avoids float32 trouble and is cheap whennis small. Steps are capped so that no coordinate moves more thanmax_step.method="lm"(Levenberg-Marquardt): step-(H + lam D)^{-1} g, withlaminitialised fromtauand 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. IfHis indefinite, or a customlinear_solverreturns an uphill step, the iteration falls back to steepest descent.
Dis the identity, ordiag(H)withdamping="marquardt".The run stops, as converged, once a step is below
step_tol(max-norm), when the gradient is exactly zero (a stationary point, whereHmay 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 abovestep_tol; it plays the role of Ceres Solver’sfunction_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, leavesxunmoved: every entry within 64 units in the last place of its scale (|x|, or the manifold’sentry_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 atx0stops the run at once.Hmay be a sparse COO or CSR tensor, for problems with many parameters but few nonzeros inJ^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)withhas_aux=True.lossis a scalar tensor,gits gradient of shape(n,)andHa positive semi-definite curvature model of shape(n, n), dense or sparse.xhas the shape ofx0. Called without gradient tracking.piazzi.least_squares_system()builds one from residuals.x0 (
torch.Tensor) – starting point, of any shape.nis its number of elements, or the tangent size ofmanifold.
- Keyword Arguments:
method (
str, optional) –"lm"(Levenberg-Marquardt) or"gn"(Gauss-Newton). Default:"lm"has_aux (
bool, optional) – whethersystemalso returns an auxiliary output (any tree of tensors), returned detached inresult.auxandinfo.aux. Default:Falsemanifold (
piazzi.Manifold, optional) – keepsxon a manifold such aspiazzi.SE3.gandHare then in tangent coordinates atx(piazzi.least_squares_system()builds them that way when given the same manifold), each step is applied asx <- manifold.plus(x, step), andmax_stepandstep_tolapply to the tangent step. Default:Nonevalue_fun (
Callable, optional) – a cheapervalue_fun(x) -> loss(or(loss, aux)) for value-only evaluations. Default:None, which uses the loss thatsystemreturns.max_iter (
int, optional) – maximum number of iterations, accepted or rejected. Default:100max_step (
float, optional) – largest change of any coordinate in one step (in the units ofx, or of the tangent vector). Default:1.0step_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 changexat all is never accepted. Default:1e-5c1 (
float, optional) – Armijo sufficient-decrease constant (method="gn"). Default:1e-4max_backtracks (
int, optional) – maximum number of step halvings in one line search (method="gn"). Default:10gn_ridge (
float, optional) – ridge added toHformethod="gn", relative tomean(diag H)(or toDwithdamping="marquardt"). Default:1e-6tau (
float, optional) – initial Levenberg-Marquardt damping, relative tomax(diag H)(or toDwithdamping="marquardt"). Default:1e-3max_rejections (
int, optional) – stop after this many rejected Levenberg-Marquardt steps in a row. Default:6damping (
str, optional) –"identity"(D = I) or"marquardt"(D = diag(H), floored at1e-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 ofx_scale="jac"inscipy.optimize.least_squares(). Default:"identity"solve_dtype (
torch.dtype, optional) – dtype of the linear solve. Default:torch.float64solve_device (
strortorch.device, optional) – device of the linear solve. Default:"cpu"linear_solver (
piazzi.LinearSolver, optional) –solver(H, g, damping) -> dsolving(H + diag(damping)) d = -g(seepiazzi.LinearSolver). Default:None, which usespiazzi.dense_solver()for a denseHandpiazzi.cg_solver()(Jacobi-preconditioned conjugate gradients, which needstorchsparsegradutils) for a sparse one.callback (
Callable, optional) – called with anpiazzi.IterationInfoafter every iteration, accepted or not; returningTruestops the run. Default:Noneverbose (
boolorint, optional) – print a table of the run’s progress withpiazzi.print_progress()before callingcallback:Trueprints every iteration and an integerkeveryk-th one. Default:False
- Returns:
OptimizeResult – the solution
x(shaped likex0), the final lossfunandaux,n_iter, the countsn_system(full system evaluations) andn_fun(value-only evaluations), andconvergedandmessage.
See also
piazzi.least_squares(): the high-level interface, which buildssystemfrom residuals withpiazzi.least_squares_system()and passes its other keyword arguments here.
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()withmethod="lm".- Parameters:
system (
Callable) –system(x) -> (loss, g, H), as forpiazzi.gauss_newton().x0 (
torch.Tensor) – starting point.**kwargs – any other keyword argument of
piazzi.gauss_newton().
- Returns:
OptimizeResult – as for
piazzi.gauss_newton().
See also
piazzi.least_squares(): the high-level interface, which runs this method by default.
- 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 (lrtimes the L-BFGS direction, scaled bymin(1, 1 / ||g||_1)while there is no curvature history, at the start or after a reset), capped so that no coordinate moves more thanmax_step. If the sufficient-decrease condition (Armijo, parameterc1) fails, the step is shrunk by quadratic interpolation up tomax_backtrackstimes. 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 fromtorch.optim.LBFGS). Every trial point requires a gradient evaluation (the curvature condition needs it), so rejected trials cost onen_fun_gradcount instead of onen_funcount.value_funis ignored whenline_search="strong_wolfe". A step that satisfies the curvature condition (parameterc2) hassᵀ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 reachedmax_step), the pair is kept only ifsᵀ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 fromLineSearches.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_epsilonbounds how far the loss may exceed its starting value for them to apply). Like strong Wolfe, every trial needs its gradient (n_fun_grad) andvalue_funis ignored. Unlike it, a step satisfying the approximate conditions may raise the loss by up tohz_epsilon * |loss|(hz_epsilon=0keeps 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 ≤ 0are 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 belowstep_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 leftxunmoved (every entry within 64 units in the last place of its scale,|x|or the manifold’sentry_scale(), at a finite value), or the loss did not measurably go up (by more than8 * eps * |loss|) while that step was belowstep_tolor predicted a decrease below rounding noise. A trial point with a non-finite value never passes the line search, and a non-finite value atx0stops the run at once.- Parameters:
fun (
Callable) –fun(x) -> loss, or(loss, aux)withhas_aux=True, wherelossis a scalar tensor differentiable with respect toxandxhas the shape ofx0.x0 (
torch.Tensor) – starting point, of any shape (it is flattened internally).
- Keyword Arguments:
has_aux (
bool, optional) – whetherfunalso returns an auxiliary output (any tree of tensors), returned detached inresult.auxandinfo.aux. Default:Falsemanifold (
piazzi.Manifold, optional) – keepsxon a manifold such aspiazzi.SE3. The gradient is then taken with respect to the tangent vectordeltaoffun(manifold.plus(x, delta))atdelta = 0, steps are applied withmanifold.plus, and the curvature pairs are kept in tangent coordinates without vector transport (as in Ceres Solver’s line-search solver).max_stepandstep_tolapply to the tangent step. Default:Nonevalue_fun (
Callable, optional) – a cheapervalue_fun(x) -> lossfor the Armijo backtracking evaluations, run undertorch.no_grad. The gradient at an accepted backtracked point then needs one more call tofun. With the default, the backtracking evaluatesfunitself and records its graph for the deferred backward pass; iffunis much cheaper without a graph, passvalue_fun=funto backtrack undertorch.no_gradinstead. Ignored whenline_search="strong_wolfe", which always needs the gradient. Default:Nonemax_iter (
int, optional) – maximum number of iterations. Default:100lr (
float, optional) – initial step length along the L-BFGS direction. Default:1.0history_size (
int, optional) – number of curvature pairs kept. Default:10line_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"needsc1 < 1/2(itsdelta). Default:1e-4c2 (
float, optional) – curvature constant of the Wolfe conditions; must satisfyc1 < c2 < 1(checked unlessline_search="armijo", which ignores it). Default:0.9hz_epsilon (
float, optional) – relative tolerance of the approximate Wolfe conditions of"hager_zhang": they apply to points whose loss is at mostloss + hz_epsilon * |loss|, so a step may raise the loss by that much;0keeps every step monotone. Ignored by the other line searches. Default:1e-6max_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 mostmax_backtracks + 1evaluations. Default:10max_step (
float, optional) – largest change of any coordinate in one step (in the units ofx, or of the tangent vector). Default:1.0step_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 movedx(1024 units in the last place of each entry’s scale), as at a float32 noise floor. Default:1e-5callback (
Callable, optional) – called with anpiazzi.IterationInfoafter every iteration, accepted or not; returningTruestops the run. Default:Noneverbose (
boolorint, optional) – print a table of the run’s progress withpiazzi.print_progress()before callingcallback:Trueprints every iteration and an integerkeveryk-th one. Default:False
- Returns:
OptimizeResult – the solution
x(shaped likex0), the final lossfunandaux,n_iter, the countsn_fun_grad(value and gradient) andn_fun(value only, Armijo backtracking only), andconvergedandmessage.
See also
piazzi.minimize(): the high-level interface, which runs this method by default and passes itsoptionshere.
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 costF = 0.5 * sum(C^2 * rho(z))withz = (r / C)^2andC = f_scale, as inscipy.optimize.least_squares(). With the defaultloss="linear"this isF = 0.5 * ||r||^2,g = J^T randH = J^T J. For a robust loss the gradient isg = J^T (rho'(z) * r)andH = J^T diag(w) J, with weightswset bycurvature. The JacobianJof shape(m, n)comes from forward-mode autodiff (torch.func.jacfwd()), which is cheap when there are few parameters. For large or structured problems, writesystemby hand and reduceJ^T Jwithout materialisingJ.- Parameters:
residual_fun (
Callable) –residual_fun(x) -> r, or(r, aux)withhas_aux=True, whereris a tensor of residuals of any shape (flattened to(m,)) andxhas the shape of the point passed tosystem.has_aux (
bool, optional) – whetherresidual_funalso returns an auxiliary output (any tree of tensors), whichsystemthen returns as a fourth element. Default:False
- Keyword Arguments:
loss (
strorCallable, optional) – a name frompiazzi.LOSSES("linear","huber","soft_l1","cauchy","arctan"), or a callablerho(z)written in PyTorch and applied elementwise, whose derivatives come from autograd. Default:"linear"f_scale (
float, optional) – soft marginCbetween inlier and outlier residuals, in the units ofr. Default:1.0curvature (
str, optional) –the weights
wofH = J^T diag(w) Jfor 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 withrho'' <= 0, which includes every built-in loss."scipy":w = max(rho'(z) + 2 * rho''(z) * z, eps), the model ofscipy.optimize.least_squares(). It is more accurate for inliers, but for outliers the bracket is negative and floored ateps. When most residuals start as outliers,His then nearly singular and Levenberg-Marquardt can stall;method="gn"copes better.
manifold (
piazzi.Manifold, optional) – keepsxon a manifold.Jis then the Jacobian ofdelta -> r(manifold.plus(x, delta))atdelta = 0, sogandHare in tangent coordinates (for example 6 columns forpiazzi.SE3). Pass the same manifold topiazzi.gauss_newton(). Default:None
- Returns:
Callable –
system(x) -> (loss, g, H), or(loss, g, H, aux)withhas_aux, withgof shape(n,)andHof shape(n, n).
See also
piazzi.least_squares(): the high-level interface, which builds and solves this system for you.