High-level interfaces

The SciPy-style entry points, and where to start. They take the objective in its most natural form (residuals, or a scalar), choose a method by name and pass that method’s settings through: least_squares() forwards its other keyword arguments, and minimize() forwards options. The method-specific solvers they run document every setting.

piazzi.least_squares(fun, x0, *, loss='linear', f_scale=1.0, method='lm', has_aux=False, curvature='irls', manifold=None, **kwargs)[source]

Minimise a sum of squared residuals, like scipy.optimize.least_squares().

Minimises 0.5 * sum(f_scale^2 * rho((r / f_scale)^2)) with r = fun(x). This builds the normal equations with piazzi.least_squares_system() and solves them with piazzi.gauss_newton(), using the residuals alone, without the Jacobian, for value-only evaluations. With a manifold such as piazzi.SE3, x0 is a point on it (a (4, 4) pose) and every iterate stays on it.

Parameters:
  • fun (Callable) – fun(x) -> r, or (r, aux) with has_aux=True, where r is a tensor of residuals of any shape and x has the shape of x0.

  • x0 (torch.Tensor) – starting point, of any shape, or a point on manifold.

Keyword Arguments:
  • loss (str or Callable, optional) – a name from piazzi.LOSSES or a callable rho(z), as in piazzi.least_squares_system(). Default: "linear"

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

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

  • 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

  • curvature (str, optional) – "irls" or "scipy", as in piazzi.least_squares_system(). Default: "irls"

  • manifold (piazzi.Manifold, optional) – keeps x on a manifold (see piazzi.Manifold). Default: None

  • **kwargs – other keyword arguments of piazzi.gauss_newton(), such as max_iter, step_tol, max_step, damping, linear_solver, callback or verbose.

Returns:

OptimizeResult – as for piazzi.gauss_newton(). result.fun is the cost, not the residuals.

See also

Example:

>>> t = torch.linspace(0, 4, 40)
>>> y = 2.5 * torch.exp(-1.3 * t)
>>> y[::10] += 2.0  # outliers
>>> def residuals(theta):
...     return theta[0] * torch.exp(-theta[1] * t) - y
>>> res = piazzi.least_squares(residuals, torch.tensor([1.0, 0.5]), loss="cauchy", f_scale=0.1)
>>> res.x
tensor([2.5026, 1.3005])
piazzi.minimize(fun, x0, method='lbfgs', *, has_aux=False, manifold=None, callback=None, verbose=False, options=None)[source]

Minimise a scalar function of a tensor, like scipy.optimize.minimize().

Gradients come from autograd. As in SciPy, method names the solver and its settings go in options. piazzi.scipy.minimize() has the same calling convention and runs SciPy’s methods, so you can swap backends to compare them.

method can also be a torch.optim.Optimizer subclass, such as torch.optim.LBFGS or torch.optim.Adam. options then holds its constructor arguments (lr, line_search_fn, …) plus piazzi’s max_iter (default 100), step_tol (stop once a step is below it in max-norm; off by default, since some optimisers, such as Rprop, skip steps) and, for LBFGS, max_eval. Each iteration is one optimiser step, callback is called after each, and every evaluation computes the value and gradient together. torch.optim.LBFGS runs one L-BFGS iteration per step, with max_iter, max_eval (default max_iter * 5 // 4) and its tolerance_grad and tolerance_change tests applied to the whole run, so it follows the same path as a single upstream step call. The point its line search accepts is not evaluated twice. result.raw is the optimiser.

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, or a point on manifold.

  • method (str or type, optional) – a name from piazzi.MINIMIZE_METHODS (case insensitive; "lbfgs", that is piazzi.lbfgs(), or "torchmin-bfgs", "torchmin-trust-exact", … for the methods of piazzi.torchmin.minimize(), which needs pytorch-minimize), or a torch.optim.Optimizer subclass (the class, not an instance). Default: "lbfgs"

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; see piazzi.lbfgs(). Not supported with torch.optim.Optimizer methods. Default: None

  • callback (Callable, optional) – called with an piazzi.IterationInfo after every iteration; 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

  • options (dict, optional) – settings for the method, for example {"max_iter": 500, "step_tol": 1e-8}. Default: None

Returns:

OptimizeResult – the method’s result; see piazzi.lbfgs().

See also

Example:

>>> def rosenbrock(x):
...     return (100 * (x[1:] - x[:-1] ** 2) ** 2 + (1 - x[:-1]) ** 2).sum()
>>> x0 = torch.tensor([-1.2, 1.0], dtype=torch.float64)
>>> piazzi.minimize(rosenbrock, x0).x
tensor([1.0000, 1.0000], dtype=torch.float64)
>>> res = piazzi.minimize(rosenbrock, x0, method=torch.optim.LBFGS, options={"line_search_fn": "strong_wolfe"})
>>> res.x
tensor([1.0000, 1.0000], dtype=torch.float64)
piazzi.finite_difference(fun, *, eps=None, scheme='central', manifold=None)[source]

Make a black-box function look differentiable, so that any solver can use it.

Use this when fun(x) -> Tensor cannot be differentiated by autograd: a non-differentiable renderer or simulator, a library working on NumPy arrays, a measurement. The returned function gives the same values as fun and has finite-difference derivatives, in forward mode (torch.func.jacfwd(), which piazzi.least_squares() uses) and in reverse mode (backward, which piazzi.minimize() uses), so solvers, manifold= and robust losses work unchanged.

Every Jacobian costs n ("forward") or 2n ("central") extra calls of fun for n parameters, which is why this is a last resort: prefer autograd where it works. The solver’s n_fun_grad counts only its own evaluations, so read the total from the n_evals attribute of the returned function, which counts every call of fun.

fun is called without gradient tracking, on a copy of its argument, and its result is copied. It must return a tensor (has_aux is not supported) and be deterministic: noise larger than the step ruins the differences. It runs on the device and in the dtype of x, and so do the differences. Prefer float64: in float32 the default step is large (about 5e-3) and a central difference is accurate to roughly 1e-3 relative error at best.

The numerics follow the numerical Jacobian of torch.autograd.gradcheck (central differences, one coordinate at a time), with the step relative to the coordinate: eps * max(|x_i|, 1).

With manifold=M, pass the same manifold to the solver. The solver differentiates fun(M.plus(x, delta)) at delta = 0; the wrapper then recovers the tangent coordinates delta of each direction and evaluates fun(M.plus(x, +-h * delta)), so fun only ever sees points on the manifold (a valid rotation matrix, say), a Jacobian costs 2 * tangent_size calls, and the step h is eps in tangent coordinates (not scaled by |x|). Without manifold=, the differences are taken in ambient space along the tangent directions, so fun is evaluated at points that leave the manifold by O(eps^2).

Parameters:

fun (Callable) – the black-box function fun(x) -> Tensor of a tensor x.

Keyword Arguments:
  • eps (float, optional) – relative step. Default: finfo.eps ** (1/3) for "central" (about 6e-6 in float64) and finfo.eps ** (1/2) for "forward", the steps that balance truncation and rounding error.

  • scheme (str, optional) – "central" (error O(eps^2), 2n calls) or "forward" (error O(eps), n calls, reusing the value at x that the solver has just computed). Default: "central"

  • manifold (piazzi.Manifold, optional) – the piazzi.Manifold that the solver is given, if any, as above. Default: None

Returns:

Callable – fd_fun(x) -> Tensor with the values of fun and finite-difference derivatives. Its n_evals attribute counts the calls of fun so far, the finite-difference ones included.

Example:

>>> def simulate(x):  # a stand-in for code that autograd cannot see through
...     y = x.detach().numpy()
...     return torch.from_numpy(y**2 + y[::-1])
>>> fd_fun = piazzi.finite_difference(simulate)
>>> target = torch.tensor([5.0, 8.0, 7.0], dtype=torch.float64)
>>> res = piazzi.least_squares(lambda x: fd_fun(x) - target, torch.ones(3, dtype=torch.float64))
>>> torch.allclose(fd_fun(res.x), target, atol=1e-6)
True
>>> fd_fun.n_evals > res.n_system  # every difference calls simulate
True
piazzi.MINIMIZE_METHODS: dict[str, Callable[..., OptimizeResult]]

Scalar minimisers available to minimize() by name (currently "lbfgs"). To add one, register a callable method(fun, x0, *, has_aux, callback, **options) under a lower-case name. minimize() passes manifold= only when one is given, so a method that doesn’t support manifolds need not accept it.