Skip to content

Fix log_loss and d2_log_loss_score type promotion mismatch - #33022

Merged
ogrisel merged 2 commits into
scikit-learn:mainfrom
betatim:fix-log_loss_dtype-promotion
Jan 8, 2026
Merged

ogrisel merged 2 commits into
scikit-learn:mainfrom
betatim:fix-log_loss_dtype-promotion

Conversation

@betatim

@betatim betatim commented Jan 7, 2026 •

Copy link
Copy Markdown
Member

What does this implement/fix? Explain your changes.

I was running pytest -k "array_api and array_api_strict" after updating main to check things were working. This came up with a group of failures like

FAILED sklearn/metrics/tests/test_classification.py::test_probabilistic_metrics_array_api[array_api_strict-device_1-float64-False-False-log_loss] - TypeError: array_api_strict.int64 and array_api_strict.float64 cannot be type promoted together
Full traceback for one test

_____________________________________________________ test_probabilistic_metrics_multilabel_array_api[array_api_strict-device_2-float32-True-d2_log_loss_score] ______________________________________________________

prob_metric = <function d2_log_loss_score at 0x155743600>, use_sample_weight = True, array_namespace = 'array_api_strict', device_ = array_api_strict.Device('device1'), dtype_name = 'float32'

    @pytest.mark.parametrize(
        "prob_metric", [brier_score_loss, log_loss, d2_brier_score, d2_log_loss_score]
    )
    @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_multilabel_array_api(
        prob_metric, 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
        multi-label inputs.
        """
        xp = _array_api_for_tests(array_namespace, device_)
        sample_weight = np.array([1, 2, 3, 1]) if use_sample_weight else None
        y_true_np = np.array(
            [
                [0, 0, 1, 1],
                [1, 0, 1, 0],
                [0, 1, 0, 0],
                [1, 1, 0, 1],
            ],
            dtype=dtype_name,
        )
        y_true_xp = xp.asarray(y_true_np, device=device_)
        y_prob_np = np.array(
            [
                [0.15, 0.27, 0.46, 0.12],
                [0.33, 0.38, 0.06, 0.23],
                [0.06, 0.28, 0.03, 0.63],
                [0.14, 0.31, 0.26, 0.29],
            ],
            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)
        with config_context(array_api_dispatch=True):
>           metric_score_xp = prob_metric(y_true_xp, y_prob_xp, sample_weight=sample_weight)
                              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

sklearn/metrics/tests/test_classification.py:3744:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
sklearn/utils/_param_validation.py:218: in wrapper
    return func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^
sklearn/metrics/_classification.py:3869: in d2_log_loss_score
    numerator = _log_loss(
sklearn/metrics/_classification.py:3393: in _log_loss
    loss = -xp.sum(xlogy(transformed_labels, y_pred), axis=1)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
../../miniconda/envs/sklearn-py3.13/lib/python3.13/site-packages/scipy/special/_support_alternative_backends.py:167: in wrapped
    return f(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^
../../miniconda/envs/sklearn-py3.13/lib/python3.13/site-packages/scipy/special/_support_alternative_backends.py:76: in __xlogy
    temp = x * xp.log(y)
           ^^^^^^^^^^^^^
../../miniconda/envs/sklearn-py3.13/lib/python3.13/site-packages/array_api_strict/_array_object.py:858: in __mul__
    other = self._check_allowed_dtypes(other, "numeric", "__mul__")
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
../../miniconda/envs/sklearn-py3.13/lib/python3.13/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.float32

    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.float32 cannot be type promoted together

../../miniconda/envs/sklearn-py3.13/lib/python3.13/site-packages/array_api_strict/_dtypes.py:229: TypeError

AI usage disclosure

I used AI assistance for:

  • Code generation (e.g., when writing an implementation or fixing a bug)
  • Test/benchmark generation
  • Documentation (including examples)
  • Research and understanding

Any other comments?

I am not sure why this doesn't happen in our CI. I use the same version of array_api_strict locally (2.4.1). Maybe it is because I use scipy 1.15.2 locally? This puzzles me.


import numpy as np
from scipy.sparse import coo_matrix, csr_matrix, issparse
from scipy.special import xlogy

@betatim betatim Jan 7, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

scipy's xlogy support array API but has a bug related to setting the right device on arrays it creates. Maybe only is scipy 1.15.2?

@betatim

betatim commented Jan 7, 2026

Copy link
Copy Markdown
Member Author

Indeed, if I upgrade to scipy 1.16 the problem goes away. Not sure if this means we should or should not fix it?

@betatim betatim added the CUDA CI label Jan 7, 2026
@github-actions github-actions Bot removed the CUDA CI label Jan 7, 2026

@virchan virchan left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for the PR, @betatim!

I can confirm the same behaviour locally. Running

pytest -k "array_api and array_api_strict"

raises errors with 1.15.2 <= scipy < 1.16.0, and passes with scipy >= 1.16.0 on the main branch. I also have array-api-strict==2.4.1 installed locally.

Comment thread sklearn/metrics/_classification.py Resolved

@ogrisel ogrisel left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Indeed, if I upgrade to scipy 1.16 the problem goes away. Not sure if this means we should or should not fix it?

Since we already have _xlogy in our code base, let's use it consistently for now.

But I would also be fine with a follow-up PR that removes _xlogy from our code base and uses scipy.special.xlogy everywhere (and therefore impose using the latest scipy version for people needing array API support).

@ogrisel
ogrisel enabled auto-merge (squash) January 8, 2026 09:26
@ogrisel ogrisel moved this to In Progress in Array API Jan 8, 2026
@ogrisel
ogrisel merged commit 255a542 into scikit-learn:main Jan 8, 2026
@github-project-automation github-project-automation Bot moved this from In Progress to Done in Array API Jan 8, 2026
@lucyleeow

lucyleeow commented Jan 8, 2026 •

Copy link
Copy Markdown
Member

I think this is (was) due to #32552
Would be interested in your opinions on bumping scipy version for array API

I noticed it too: #32422 (comment)

@lesteve

lesteve commented Jan 8, 2026

Copy link
Copy Markdown
Member

Would be interested in your opinions on bumping scipy version for array API

There was some comment somewhere that was pointing to a regression in scipy 1.16 I think? #32552 (comment)

I ran a poll #32552 (comment) a couple of months ago where nobody had strong opinions.

dschult pushed a commit to dschult/scikit-learn that referenced this pull request Jan 25, 2026
dschult pushed a commit to dschult/scikit-learn that referenced this pull request Jan 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Archived in project

Development

Successfully merging this pull request may close these issues.

5 participants