SciPy backend

Wrappers that run SciPy’s solvers on PyTorch functions, with the calling conventions of piazzi.least_squares() and piazzi.minimize(), so you can compare backends on the same problem. Requires the piazzi[scipy] extra; import piazzi does not load it. See the backends guide.

piazzi.scipy.least_squares(fun, x0, *, jac='autodiff', loss='linear', f_scale=1.0, bounds=(-inf, inf), callback=None, verbose=False, **kwargs)[source]

Run scipy.optimize.least_squares() on a residual function written in PyTorch.

fun runs in the dtype and on the device of x0; SciPy itself works in float64 on the CPU, and the wrapper converts at each call. Unlike SciPy, the default Jacobian comes from forward-mode autodiff, as in piazzi.least_squares(), so the two run on the same derivatives.

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

  • x0 (torch.Tensor) – starting point, of any shape.

Keyword Arguments:
  • jac (str or Callable, optional) – "autodiff" for torch.func.jacfwd(); a callable jac(x) -> J returning a tensor of shape (m, n); or one of SciPy’s finite-difference schemes, "2-point" or "3-point" (not "cs"). Finite differences need a float64 x0: in float32 their steps are lost to rounding. Default: "autodiff"

  • loss (str or Callable, optional) – a SciPy loss name, or a callable rho(z) written in PyTorch as for piazzi.least_squares(); the wrapper gives SciPy its derivatives from autograd. Default: "linear"

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

  • bounds (tuple or scipy.optimize.Bounds, optional) – as in SciPy, a (lb, ub) pair or a scipy.optimize.Bounds. Tensors and arrays in it are converted and flattened to match the flat x0; 0-dim ones are scalars. Default: (-inf, inf)

  • callback (Callable, optional) – called after every iteration with an piazzi.IterationInfo, as for the native solvers (fun is the cost; aux is None); returning True stops the run. Needs SciPy 1.16 or later. 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. It takes the place of SciPy’s own verbose, and like callback needs SciPy 1.16 or later. Default: False

  • **kwargs – other keyword arguments of scipy.optimize.least_squares() (method, ftol, xtol, gtol, max_nfev, x_scale, …). Tensors given as x_scale or diff_step are converted like bounds. As in SciPy, args=(...) and kwargs={...} hold extra positional and keyword arguments for fun and a callable jac (not options for SciPy); both are empty by default.

Returns:

OptimizeResult – x with the shape, dtype and device of x0, and fun the cost. SciPy does not report iterations, so n_iter is its Jacobian evaluation count (njev), or nfev when njev is not reported. The counts are calls the wrapper made: n_fun residual evaluations (including those of finite differences, which SciPy’s nfev leaves out for "trf" and "dogbox") and n_system Jacobian evaluations (jac="autodiff" or a callable). converged is SciPy’s success, and raw is SciPy’s own result.

See also

Example:

>>> t = torch.linspace(0, 4, 40, dtype=torch.float64)
>>> y = 2.5 * torch.exp(-1.3 * t)
>>> x0 = torch.tensor([1.0, 0.5], dtype=torch.float64)
>>> res = piazzi.scipy.least_squares(lambda p: p[0] * torch.exp(-p[1] * t) - y, x0)
>>> res.x
tensor([2.5000, 1.3000], dtype=torch.float64)
piazzi.scipy.minimize(fun, x0, method=None, *, jac='autodiff', hess=None, hessp=None, bounds=None, has_aux=False, callback=None, verbose=False, options=None, **kwargs)[source]

Run scipy.optimize.minimize() on a scalar function written in PyTorch.

It has the calling convention of piazzi.minimize() (fun, x0, method, has_aux, callback and options), so you can swap backends to compare them; method and the keys of options are SciPy’s. fun runs in the dtype and on the device of x0; SciPy itself works in float64 on the CPU, and the wrapper converts at each call. Use a float64 x0 for tight tolerances: SciPy’s line searches and finite differences struggle with float32 noise.

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

  • x0 (torch.Tensor) – starting point, of any shape.

  • method (str or Callable, optional) – any SciPy method ("BFGS", "L-BFGS-B", "Newton-CG", "trust-exact", …). Default: None, which lets SciPy choose.

Keyword Arguments:
  • jac (str or Callable, optional) – "autodiff" computes the value and gradient together with autograd, in one evaluation; a callable jac(x) -> grad in PyTorch; or SciPy’s finite differences ("2-point", "3-point", or None; not "cs"). Methods that use no gradient (Nelder-Mead, Powell, COBYLA, COBYQA) get none. Default: "autodiff"

  • hess (str or Callable, optional) – "autodiff" for the exact Hessian from autograd; a callable hess(x) -> H in PyTorch returning a tensor of shape (n, n); or anything SciPy accepts ("2-point", or a scipy.optimize.HessianUpdateStrategy such as scipy.optimize.BFGS). Only Newton-type and trust-region methods use it. Default: None

  • hessp (str or Callable, optional) – "autodiff" for Hessian-vector products from autograd (double backward), or a callable hessp(x, p) -> H @ p in PyTorch. Default: None

  • bounds (scipy.optimize.Bounds or torch.Tensor, optional) – as in SciPy; a scipy.optimize.Bounds holding tensors, or a tensor of shape (n, 2) of (min, max) pairs, is converted. Default: None

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

  • callback (Callable, optional) – called after every iteration with an piazzi.IterationInfo (tensors, with the evaluation counts so far), as for the native solvers; returning True stops the run. aux is set when SciPy’s last evaluation was at the iterate. TNC reports only x (fun is then NaN unless known) and cannot be stopped. 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) – SciPy’s method-specific options. Default: None

  • args (tuple, optional) – as in SciPy, extra arguments for fun and callable jac, hess and hessp. Default: ()

  • **kwargs – other keyword arguments of scipy.optimize.minimize() (tol, constraints, …). Constraint functions receive NumPy arrays.

Returns:

OptimizeResult – x with the shape, dtype and device of x0, fun the final value and aux its auxiliary output (with has_aux). n_iter is SciPy’s nit. The counts are calls the wrapper made, not SciPy’s nfev / njev / nhev: n_fun_grad counts value-and-gradient evaluations (jac="autodiff") or calls to a callable jac, n_fun value-only ones (including finite-difference ones), and n_system Hessian or Hessian-vector product evaluations. converged is SciPy’s success, and raw is SciPy’s own result. fun and aux come from the last evaluation at SciPy’s final x; if SciPy did not evaluate there last, the wrapper evaluates fun once more, which the counts do not include.

See also

Example:

>>> def rosenbrock(x):
...     return (100 * (x[1:] - x[:-1] ** 2) ** 2 + (1 - x[:-1]) ** 2).sum()
>>> res = piazzi.scipy.minimize(rosenbrock, torch.tensor([-1.2, 1.0], dtype=torch.float64), method="BFGS")
>>> res.x
tensor([1.0000, 1.0000], dtype=torch.float64)
piazzi.scipy.t2n(x)[source]

Convert a tensor to a float64 NumPy array, as the SciPy wrappers do.

Always an owned copy: for a CPU float64 tensor .numpy() alone would alias its storage. SciPy’s robust-loss scaling is written to work in place (f *= ..., copy=False); current versions copy first, but a view of PyTorch storage should never depend on that.

Parameters:

x (torch.Tensor) – a tensor on any device, of any dtype and shape.

Returns:

numpy.ndarray – a detached float64 copy, with the shape of x.

piazzi.scipy.n2t(a, like)[source]

Convert an array-like to a tensor, as the SciPy wrappers do.

Parameters:
  • a (array_like) – a NumPy array, scalar or nested sequence.

  • like (torch.Tensor) – the tensor whose dtype and device the result takes.

Returns:

Tensor – a copy of a with the dtype and device of like.