Skip to content

Array API test failure for probabilistic metrics with scipy==1.15.0 #32552

Closed

Description

@StefanieSenger

Describe the bug

In #32422 we have introduced array API for probabilistic metrics and added a test (test_probabilistic_metrics_multilabel_array_api).

I had this test failing locally with scipy==1.15.0 for array-api-strict arrays on log_loss and 2d_log_loss_score, because scipy's xlogy of that version (used in _log_loss) has trouble handling array-api-strict arrays of mixed dtypes (int64 and float64).

According to sklearn/utils/_array_api.py the scipy min version for array api would be "1.14.0". Theoretically "1.15.0" should not throw an error. I am not sure what we can do about this, and if we need to, since all array libraries pass this test and it is only array-api-strict failing. We could move the internal min_scipy_version, but apart from that I cannot see any fix we could do internally.

Talking with @lesteve, he advised me to open an issue, be it just indicating to others who stumble over the same issue that upgrading scipy is the solution. @lesteve Thanks for your help in fixing this.

Traceback

prob_metric = <function log_loss at 0x7f97095f5580>, str_y_true = False, use_sample_weight = False, array_namespace = 'array_api_strict'
device_ = array_api_strict.Device('CPU_DEVICE'), dtype_name = 'float64'
    @pytest.mark.parametrize(
        "prob_metric", [brier_score_loss, log_loss, d2_brier_score, d2_log_loss_score]
    )
    @pytest.mark.parametrize("str_y_true", [False, True])
    @pytest.mark.parametrize("use_sample_weight", [False, True])
    @pytest.mark.parametrize(
        "array_namespace, device_, dtype_name", yield_namespace_device_dtype_combinations()
    )
    def test_probabilistic_metrics_array_api(
        prob_metric, str_y_true, use_sample_weight, array_namespace, device_, dtype_name
    ):
        """Test that :func:`brier_score_loss`, :func:`log_loss`, func:`d2_brier_score`
        and :func:`d2_log_loss_score` work correctly with the array API for binary
        and mutli-class inputs.
        """
        xp = _array_api_for_tests(array_namespace, device_)
        sample_weight = np.array([1, 2, 3, 1]) if use_sample_weight else None
    
        # binary case
        extra_kwargs = {}
        if str_y_true:
            y_true_np = np.array(["yes", "no", "yes", "no"])
            y_true_xp_or_np = np.asarray(y_true_np)
            if "brier" in prob_metric.__name__:
                # `brier_score_loss` and `d2_brier_score` require specifying the
                # `pos_label`
                extra_kwargs["pos_label"] = "yes"
        else:
            y_true_np = np.array([1, 0, 1, 0])
            y_true_xp_or_np = xp.asarray(y_true_np, device=device_)
    
        y_prob_np = np.array([0.5, 0.2, 0.7, 0.6], dtype=dtype_name)
        y_prob_xp = xp.asarray(y_prob_np, device=device_)
        metric_score_np = prob_metric(
            y_true_np, y_prob_np, sample_weight=sample_weight, **extra_kwargs
        )
        with config_context(array_api_dispatch=True):
>           metric_score_xp = prob_metric(
                y_true_xp_or_np, y_prob_xp, sample_weight=sample_weight, **extra_kwargs
            )

sklearn/metrics/tests/test_classification.py:3712: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
sklearn/utils/_param_validation.py:218: in wrapper
    return func(*args, **kwargs)
sklearn/metrics/_classification.py:3363: in log_loss
    return _log_loss(
sklearn/metrics/_classification.py:3378: in _log_loss
    loss = -xp.sum(xlogy(transformed_labels, y_pred), axis=1)
../../../.pyenv/versions/scikit-learn_dev/lib/python3.12/site-packages/scipy/special/_support_alternative_backends.py:167: in wrapped
    return f(*args, **kwargs)
../../../.pyenv/versions/scikit-learn_dev/lib/python3.12/site-packages/scipy/special/_support_alternative_backends.py:76: in __xlogy
    temp = x * xp.log(y)
../../../.pyenv/versions/scikit-learn_dev/lib/python3.12/site-packages/array_api_strict/_array_object.py:858: in __mul__
    other = self._check_allowed_dtypes(other, "numeric", "__mul__")
../../../.pyenv/versions/scikit-learn_dev/lib/python3.12/site-packages/array_api_strict/_array_object.py:215: in _check_allowed_dtypes
    res_dtype = _result_type(self.dtype, other.dtype)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

type1 = array_api_strict.int64, type2 = array_api_strict.float64

    def _result_type(type1: DType, type2: DType) -> DType:
        if (type1, type2) in _promotion_table:
            return _promotion_table[type1, type2]
>       raise TypeError(f"{type1} and {type2} cannot be type promoted together")
E       TypeError: array_api_strict.int64 and array_api_strict.float64 cannot be type promoted together

../../../.pyenv/versions/scikit-learn_dev/lib/python3.12/site-packages/array_api_strict/_dtypes.py:229: TypeError

Versions

scipy==1.15.0

Activity

  1. StefanieSenger commented on Oct 22, 2025

    @StefanieSenger
    MemberAuthor

    It seems that #scipy/22946 then fixed that. It went into the 1.16 release.

  2. lesteve commented on Oct 22, 2025

    @lesteve
    Member

    Thanks for providing all the info, that will make it easier for others to fix the issue, if they bumps into this problem.

    I guess not doing anything seems the main option, since it seems only specific to array-api-strict. My expectations is that most (if not all) of the array-API supporting libraries will support multiplying an array of float64 with an array of int64.

    The alternative is to say that if scipy >= 1.16 as our minimum scipy version if you want array API support. Since array API support is experimental and scipy has been fixing things, I think it is is fine to require somewhat recent versions of our dependencies.

    The code setting our minimum scipy version for array API support is there:

    min_scipy_version = "1.14.0"
    if scipy_version < parse_version(min_scipy_version):
    raise ImportError(
    f"SciPy must be {min_scipy_version} or newer"
    " (found {scipy.__version__}) to dispatch array using"
    " the array API specification"

  3. StefanieSenger commented on Oct 22, 2025

    @StefanieSenger
    MemberAuthor

    I'm in favour of min_scipy_version = "1.16.0", so it's clear for everybody involved within scikit-learn and nobody needs to wonder about this in future.

  4. lesteve commented on Oct 22, 2025

    @lesteve
    Member

    The downside though is that you will require all our users who wants to use API support to update scipy to a more recent version, scipy 1.14 (released 2024) -> scipy 1.16 (released June 2025) (source https://pypi.org/project/scipy/#history)

    Not saying this is the end of the world, but it's good to bear this in mind when deciding about the trade-offs 😉.

  5. StefanieSenger commented on Oct 22, 2025

    @StefanieSenger
    MemberAuthor

    Yea, but it's a bug that is not solvable in our library to my knowledge ...
    Requiering people to update scipy is better than allowing a bug, I think.

    But I am also happy to just close this issue without doing anything and then it's documented for those who search for it.

    What do others think?

  6. changed the title [-]test_probabilistic_metrics_multilabel_array_api test failure with scipy==1.15.0[/-] [+]Array API test failure for probabilistic metrics with scipy==1.15.0[/+] on Oct 22, 2025
  7. lesteve commented on Oct 22, 2025

    @lesteve
    Member

    Yea, but it's a bug that is not solvable in our library to my knowledge ... Requiering people to update scipy is better than allowing a bug, I think.

    That's the thing: I don't think this is a real bug as this seems specific to array-api-strict that is overly picky by trying to stick very close to the array API SPEC. No "real" array API conforming library (numpy, PyTorch, CuPy, etc ...) will be affected by this as they all likely will very happily multiply an array of int64 by an array of float64.

  8. StefanieSenger commented on Oct 22, 2025

    @StefanieSenger
    MemberAuthor

    That's the thing: I don't think this is a real bug

    Oh true, sorry, I have been multi-tasking when I wrote this, and didn't think myself back in.
    I will just close this issue.

  9. lesteve commented on Oct 23, 2025

    @lesteve
    Member

    I mean I don't know and I would be curious to have other opinions on this @lucyleeow @OmarManzoor. To try to sum up:

    • our array API tests fail for scipy 1.15 (in the CI we use the latest scipy versions)
    • it's only array-api-strict which seems overly picky about refusing to multiply an array of int64 by an array of float64. I think most "real" libraries (PyTorch, CuPy, etc ...) will happily do it.
    • should we bump the minimum scipy version to 1.16? Use the 👍 or 👎 reaction (or 😕 if you have no strong opinion) 1
      • downside is that you will force users that care about array API support to get a more recent scipy version. In most cases using scipy 1.14 or scipy 1.15 may just work fine.
      • upside is that it's probably a good idea to use more recent scipy versions since scipy has been fixing bugs (in some cases you may get weird scipy errors). Also less opportunity for scikit-learn developers to bump into this kind of weird errors when running the tests and spend some time debugging it.

    Footnotes

    1. I personally voted +0.5 with both 👍 and 😕 ↩

  10. OmarManzoor commented on Oct 23, 2025

    @OmarManzoor
    Contributor

    Overall I do think it might be better to update the scipy version especially when considering array API support however I also understand the point about forcing users to upgrade the scipy version just for the case described in this issue.
    Even though this might be a case where the array API updates will just work fine aside from array-api-strict there might be other cases which might cause problems as we support more areas that use scipy functions within.
    However I also noted a scipy function which actually gets slower on larger arrays in 1.16 as compared to 1.15 scipy/scipy#23670, therefore I am not sure what version should we force as the minimum dependency.

  11. lucyleeow commented on Oct 24, 2025

    @lucyleeow
    Member

    Sorry I am no help in coming to a decision. Similar thoughts as Omar, array API is 'experimental' and it would be okay to require most/more recent scipy but I did see scipy/scipy#23670 .

    Let's drag @betatim into this 😅

  12. lesteve commented on Oct 28, 2025

    @lesteve
    Member

    tl;dr this sounds like "let's not do anything for now and revisit later!".

    I was not aware of the scipy performance regression in 1.16, so let's not change our "minimum scipy version for array API" for now.

  13. lucyleeow commented on Jan 9, 2026

    @lucyleeow
    Member

    It seems that so far we are amending our code to avoid this error:

                if xp.__name__ == "array_api_strict":
                    # in array_api_strict, int64 and float64 cannot be promoted together
                    y_true = xp.astype(xp.asarray(y_true), xp.float64, copy=False)

    I don't think the amendments are ideal, but I would be okay with it - I just wanted to raise this so we can discuss and make a conscious decision/have a plan (e.g., add todos to remove when scipy version allows) and all be onboard when we review PRs, to ensure consistency.

    cc also @ogrisel

  14. lucyleeow commented on Jan 22, 2026

    @lucyleeow
    Member

    Okay I did some digging and the problem in #32909 is indeed unrelated to this error here. As @StefanieSenger explains (#32909 (comment)) the first one is simply the fact that strict does not support mixed type promotion in its functions, whereas many (most?) array libraries do.

    The problem in here is due to a scipy change in behaviour.

    I could not figure out if/how scipy/scipy#22946 fixed this problem. AFAICT the xp_capabilities decorator is for:

        # @xp_capabilities decorator, for the purpose of
        # documentation and unit testing
    

    It may be related to scipy/scipy#22695, which was also included in 1.16 (so fit the versions of scipy that pass/fail).

    Matt explains it quite well here: https://github.com/scipy/scipy/pull/22695/files#r1997905891

    Summary:

    • Most array backends support mixed type promotion, its only strict that doesn't.
    • scipy has decided (for now) to define their own rule, "use the result type of the default float and any other floats passed."
      • this fixes many test failures with strict
      • reduces code for handling dtypes in different backends
      • this rule is implemented in 'most places already'
      • although it can result in over-promotion,

    In light of this, maybe we could consider having a TODO to remove the code alterations we have made for strict type promotion errors (e.g., #33022), once our min scipy version is >=1.16 - UNLESS we specifically do not want to type promote / worried about over-promotion. The changes in #33022 simply do the same type promotion as scipy already does so that does not apply here.
    The reason is mostly code simplicity, though I can see it does not add many lines so it's fine to keep it too.

  15. StefanieSenger commented on Jan 23, 2026

    @StefanieSenger
    MemberAuthor

    Thank you for all the digging, @lucyleeow.

    Do you mean to have a #TODO comment for when scipy>=1.16 to then remove the additional type promotions? I'm all for it, since I value code simplicity. :)

  16. lucyleeow commented on Jan 25, 2026

    @lucyleeow
    Member

    #TODO comment for when scipy>=1.16 to then remove the additional type promotions

    Yes!

  17. lesteve commented on Jan 26, 2026

    @lesteve
    Member

    I double-checked that scipy/scipy#23670 was fixed in scipy 1.17 released January 10 2026.

    If that makes our life easier, I think it's fine to require scipy >= 1.16 or even 1.17 for array API support.

    For completeness my tweaked benchmark script ran in Colab

    %env SCIPY_ARRAY_API=1
    %pip install scipy==1.17.0
    import scipy
    import torch as xp
    from scipy.special import logsumexp
    from time import time
    
    
    pred = xp.rand((100000, 500), dtype=xp.float64, device="cuda")
    timings = []
    for _ in range(10):
      start = time()
      output = logsumexp(pred, axis=1)
      # force synchronisation my moving things to CPU to make sure CUDA timing is accurate
      output[0].item()
      end = time()
      timings.append(end - start)
    
    avg_time_taken = sum(timings) / 10
    print(f"Scipy version {scipy.__version__}: avg time taken for logsumexp = {end - start}")

    Result for different scipy versions:

    Scipy version 1.15.3: avg time taken for logsumexp = 0.028291940689086914
    Scipy version 1.16.3: avg time taken for logsumexp = 0.3263514041900635
    Scipy version 1.17.0: avg time taken for logsumexp = 0.03630399703979492
    
  18. StefanieSenger commented on Jan 26, 2026

    @StefanieSenger
    MemberAuthor

    With #33139, I think we would have a nice and clear rule to only depend on the newest versions which makes developing most easy and will reduce future discussions on similar issues.

    I would prefer to update the dependencies then to scipy 1.17 over adding comments.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Array APIBugNeeds Triage

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions