Skip to content

wip: experiment with alternative to scipy.optimize.minimize_scalar - #32107

Closed
lucascolley wants to merge 3 commits into
scikit-learn:mainfrom
lucascolley:31869
Closed

lucascolley wants to merge 3 commits into
scikit-learn:mainfrom
lucascolley:31869

Conversation

@lucascolley

@lucascolley lucascolley commented Sep 4, 2025 •

Copy link
Copy Markdown
Contributor
scikit-learn on 🎋 31869 via 🐍 
❯ pwd
/Users/lucascolley/ghq/github.com/glemaitre/python-stack/scikit-learn/scikit-learn

scikit-learn on 🎋 31869 via 🐍 
❯ pixi run tests -t sklearn.tests.test_calibration
✨ Pixi task (tests in dev): spin test -t sklearn.tests.test_calibration
{snip}
sklearn/tests/test_calibration.py ..................................................s................................................................                                                [100%]

=============================================================================== 114 passed, 1 skipped, 33 warnings in 9.70s ================================================================================

gh-32107 show the existing test-suite passing while naïvely replacing minimize_scalar with bracket_minimum and find_minimum (benchmarks may be a different matter).

As documented at https://scipy.github.io/devdocs/dev/api-dev/array_api_modules_tables/optimize_elementwise.html, these functions have CuPy and PyTorch support, so this may be an interesting starting point for you @OmarManzoor @lucyleeow !

I haven't investigated performance for NumPy at all, but this may at least get you by as a fallback for non-NumPy arrays, while you wait for some more ticks to materialise in https://scipy.github.io/devdocs/dev/api-dev/array_api_modules_tables/optimize.html.

Originally posted by @lucascolley in #31869

@lucascolley lucascolley changed the title wip: experiment with alternative to minimize_scalar wip: experiment with alternative to scipy.optimize.minimize_scalar Sep 4, 2025
@github-actions

github-actions Bot commented Sep 4, 2025

Copy link
Copy Markdown

✔️ Linting Passed

All linting checks passed. Your pull request is in excellent shape! ☀️

Generated for commit: 6f0211e. Link to the linter CI: here

@OmarManzoor

Copy link
Copy Markdown
Contributor

@lucascolley

I tried these functions but they do not seem to work for different array namespaces. bracket_minimum seems to fail for both torch and array_api_strict and if you pre compute the bracket beforehand and then set it in find_minimum I think even if we organize the func to receive and return xp arrays it fails for array_api_strict.

Below is a minimum snippet I was just using which fails for bracket_minimum

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 float

Am I using these incorrectly?

@lucascolley

Copy link
Copy Markdown
Contributor Author

Yes, IIRC the implementation relies on non-standard indexing unfortunately. @mdhaber would know more.

@OmarManzoor

OmarManzoor commented Sep 24, 2025 •

Copy link
Copy Markdown
Contributor

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 minimize_scalar by converting the outputs of func to float and optimizing the actual computations done inside func via the array API.

@mdhaber

mdhaber commented Sep 24, 2025 •

Copy link
Copy Markdown
Contributor

Non-standard being fancy indexing assignment. So standard, but not in the standard.

bracket_minimum tests fail with Torch because of data-apis/array-api-compat#271, or at least that stopped further testing.

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.

@OmarManzoor

Copy link
Copy Markdown
Contributor

Got it. Thank you for the clarification

@OmarManzoor

Copy link
Copy Markdown
Contributor

@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 bracket_minimum and find_minimum and the discussions surrounding them which would still be available even after closing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants