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.funruns in the dtype and on the device ofx0; 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 inpiazzi.least_squares(), so the two run on the same derivatives.- Parameters:
fun (
Callable) –fun(x) -> r, wherexhas the shape ofx0andris a tensor of residuals of any shape.x0 (
torch.Tensor) – starting point, of any shape.
- Keyword Arguments:
jac (
strorCallable, optional) –"autodiff"fortorch.func.jacfwd(); a callablejac(x) -> Jreturning 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 float64x0: in float32 their steps are lost to rounding. Default:"autodiff"loss (
strorCallable, optional) – a SciPy loss name, or a callablerho(z)written in PyTorch as forpiazzi.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 ofr. Default:1.0bounds (
tupleorscipy.optimize.Bounds, optional) – as in SciPy, a(lb, ub)pair or ascipy.optimize.Bounds. Tensors and arrays in it are converted and flattened to match the flatx0; 0-dim ones are scalars. Default:(-inf, inf)callback (
Callable, optional) – called after every iteration with anpiazzi.IterationInfo, as for the native solvers (funis the cost;auxisNone); returningTruestops the run. Needs SciPy 1.16 or later. 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. It takes the place of SciPy’s ownverbose, and likecallbackneeds 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 asx_scaleordiff_stepare converted likebounds. As in SciPy,args=(...)andkwargs={...}hold extra positional and keyword arguments forfunand a callablejac(not options for SciPy); both are empty by default.
- Returns:
OptimizeResult –
xwith the shape, dtype and device ofx0, andfunthe cost. SciPy does not report iterations, son_iteris its Jacobian evaluation count (njev), ornfevwhennjevis not reported. The counts are calls the wrapper made:n_funresidual evaluations (including those of finite differences, which SciPy’snfevleaves out for"trf"and"dogbox") andn_systemJacobian evaluations (jac="autodiff"or a callable).convergedis SciPy’ssuccess, andrawis SciPy’s own result.
See also
piazzi.least_squares(): the native solver with the same calling convention.
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,callbackandoptions), so you can swap backends to compare them;methodand the keys ofoptionsare SciPy’s.funruns in the dtype and on the device ofx0; SciPy itself works in float64 on the CPU, and the wrapper converts at each call. Use a float64x0for tight tolerances: SciPy’s line searches and finite differences struggle with float32 noise.- Parameters:
fun (
Callable) –fun(x) -> loss, or(loss, aux)withhas_aux=True, wherexhas the shape ofx0andlossis a scalar tensor.x0 (
torch.Tensor) – starting point, of any shape.method (
strorCallable, optional) – any SciPy method ("BFGS","L-BFGS-B","Newton-CG","trust-exact", …). Default:None, which lets SciPy choose.
- Keyword Arguments:
jac (
strorCallable, optional) –"autodiff"computes the value and gradient together with autograd, in one evaluation; a callablejac(x) -> gradin PyTorch; or SciPy’s finite differences ("2-point","3-point", orNone; not"cs"). Methods that use no gradient (Nelder-Mead, Powell, COBYLA, COBYQA) get none. Default:"autodiff"hess (
strorCallable, optional) –"autodiff"for the exact Hessian from autograd; a callablehess(x) -> Hin PyTorch returning a tensor of shape(n, n); or anything SciPy accepts ("2-point", or ascipy.optimize.HessianUpdateStrategysuch asscipy.optimize.BFGS). Only Newton-type and trust-region methods use it. Default:Nonehessp (
strorCallable, optional) –"autodiff"for Hessian-vector products from autograd (double backward), or a callablehessp(x, p) -> H @ pin PyTorch. Default:Nonebounds (
scipy.optimize.Boundsortorch.Tensor, optional) – as in SciPy; ascipy.optimize.Boundsholding tensors, or a tensor of shape(n, 2)of(min, max)pairs, is converted. Default:Nonehas_aux (
bool, optional) – whetherfunalso returns an auxiliary output (any tree of tensors), returned detached inresult.aux. Default:Falsecallback (
Callable, optional) – called after every iteration with anpiazzi.IterationInfo(tensors, with the evaluation counts so far), as for the native solvers; returningTruestops the run.auxis set when SciPy’s last evaluation was at the iterate. TNC reports onlyx(funis then NaN unless known) and cannot be stopped. 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:Falseoptions (
dict, optional) – SciPy’s method-specific options. Default:Noneargs (
tuple, optional) – as in SciPy, extra arguments forfunand callablejac,hessandhessp. Default:()**kwargs – other keyword arguments of
scipy.optimize.minimize()(tol,constraints, …). Constraint functions receive NumPy arrays.
- Returns:
OptimizeResult –
xwith the shape, dtype and device ofx0,funthe final value andauxits auxiliary output (withhas_aux).n_iteris SciPy’snit. The counts are calls the wrapper made, not SciPy’snfev/njev/nhev:n_fun_gradcounts value-and-gradient evaluations (jac="autodiff") or calls to a callablejac,n_funvalue-only ones (including finite-difference ones), andn_systemHessian or Hessian-vector product evaluations.convergedis SciPy’ssuccess, andrawis SciPy’s own result.funandauxcome from the last evaluation at SciPy’s finalx; if SciPy did not evaluate there last, the wrapper evaluatesfunonce more, which the counts do not include.
See also
piazzi.minimize(): the native interface with the same calling convention.
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
awith the dtype and device oflike.