Repository navigation
wip: experiment with alternative to scipy.optimize.minimize_scalar - #32107
lucascolley wants to merge 3 commits into
Conversation
scipy.optimize.minimize_scalar
[skip ci]
|
I tried these functions but they do not seem to work for different array namespaces. Below is a minimum snippet I was just using which fails for import numpy as np
# import array_api_strict as xp
import torch as xp
from scipy.optimize.elementwise import bracket_minimum, find_minimum
from scipy.special import logsumexp
def run_check():
logits_np = np.random.rand(1000, 5).astype(np.float64)
y_np = np.random.randint(0, 5, 1000).astype(np.float64)
logits = xp.asarray(logits_np)
y_ = xp.asarray(y_np)
dtype_ = logits.dtype
def func(log_beta=xp.asarray(0.0)):
log_beta = xp.asarray(log_beta, dtype=dtype_)
pred = xp.exp(log_beta) * logits
log_sum_exp = logsumexp(pred, axis=1)
y = xp.asarray(y_, dtype=xp.int64)
class_margins = xp.asarray(xp.arange(y.shape[0])) * pred.shape[1]
label_predictions = xp.take(xp.reshape(pred, (-1,)), y + class_margins)
return xp.mean(log_sum_exp - label_predictions)
xatol = 64 * xp.finfo(dtype_).eps
func_bracket = bracket_minimum(func, xp.asarray(0), xmin=xp.asarray(-10), xmax=xp.asarray(10))
find_minimum(func, func_bracket.bracket, tolerances={"xatol": xatol})
run_check()
# array_api_strict
IndexError: Fancy indexing __setitem__ is not supported.
# torch
TypeError: minimum(): argument 'other' (position 2) must be Tensor, not floatAm I using these incorrectly? |
|
Yes, IIRC the implementation relies on non-standard indexing unfortunately. @mdhaber would know more. |
I see then I think this might not be a suitable replacement for now. I think we can just use the current |
|
Non-standard being fancy indexing assignment. So standard, but not in the standard.
Otherwise, tests of these functions pass with CuPy and Torch. According to the test decorators, no JAX because of in-place assignment in general, no array-api-strict because of fancy indexing assignment, and no Dask because of boolean indexing assignment. |
|
Got it. Thank you for the clarification |
|
@lucascolley and @mdhaber Thank you for the guidance and clarifications! I am closing this as this PR is mainly a sample of how to use |
Originally posted by @lucascolley in #31869