Skip to content

DEBUG torch incompatibility with np.sum and np.repeat (pure debug PR, will be closed soon) - #33028

Closed
StefanieSenger wants to merge 15 commits into
scikit-learn:mainfrom
StefanieSenger:debug_array_api_average_precision_score
Closed

StefanieSenger wants to merge 15 commits into
scikit-learn:mainfrom
StefanieSenger:debug_array_api_average_precision_score

Conversation

@StefanieSenger

@StefanieSenger StefanieSenger commented Jan 9, 2026 •

Copy link
Copy Markdown
Member

This is to debug a CI failure in #32909 and discuss solutions.

Specifically this discussion: https://github.com/scikit-learn/scikit-learn/pull/32909/changes#r2627102404

EDIT: It is a bug on main (#33028 (comment)) and does not only affect the mentioned PR.

@lucyleeow

lucyleeow commented Jan 9, 2026 •

Copy link
Copy Markdown
Member

Looking at the CI pipeline output, it seems that y_true gets converted to numpy first (maybe by y_type = type_of_target(y_true, input_name="y_true") ?), then within _average_binary_score y_score also gets converted to numpy (by check_array) but sample_weight is still a torch tensor. This seems to cause the failure.

The question I was asking is then, does the following give the same error on main:

import torch
from sklearn import config_context
from sklearn.metrics import average_precision_score

y_scores = torch.tensor([0.1, 0.4, 0.35, 0.8], device='cpu')
y_true = torch.tensor([0, 0, 1, 1], device='cpu')
sw = torch.tensor([1, 2, 1, 1], device='cpu')
with config_context(array_api_dispatch=False):
    average_precision_score(y_true, y_scores, sample_weight=sw)

I tried locally and it does not error for me. Does it work for you @StefanieSenger ?

If it works it means we've changed something in this PR, such that sample weight is no longer converted to numpy.
It would be nice to figure out why?

@StefanieSenger

StefanieSenger commented Jan 13, 2026 •

Copy link
Copy Markdown
Member Author

Now I see.

I tried locally and it does not error for me. Does it work for you @StefanieSenger ?

It doesn't error for me either. Sorry, I didn't understand what "it" was referring to before you posted the code.

It would have never occurred to me that feeding torch types into average_precision_score on main would be something we would expect to pass (since we have not worked on it to accept arrays other than numpy). Actually, I thought it is on me to make sure that works while I introduce array api support, since that extra test added in #30454 only runs for functions with array api support.

This one.

# When array API dispatch is disabled, and np.asarray works (for example PyTorch
# with CPU device), calling the metric function with such numpy compatible inputs
# should work (albeit by implicitly converting to numpy arrays instead of
# dispatching to the array library).
try:
np.asarray(a_xp)
np.asarray(b_xp)
numpy_as_array_works = True
except (TypeError, RuntimeError, ValueError):
# PyTorch with CUDA device and CuPy raise TypeError consistently.
# array-api-strict chose to raise RuntimeError instead. NumPy raises
# a ValueError if the `__array__` dunder does not return an array.
# Exception type may need to be updated in the future for other libraries.
numpy_as_array_works = False
def _check_metric_matches(metric_a, metric_b, convert_a=False):
if convert_a:
metric_a = _convert_to_numpy(xp.asarray(metric_a), xp)
assert_allclose(metric_a, metric_b, atol=_atol_for_type(dtype_name))
def _check_each_metric_matches(metric_a, metric_b, convert_a=False):
for metric_a_val, metric_b_val in zip(metric_a, metric_b):
_check_metric_matches(metric_a_val, metric_b_val, convert_a=convert_a)
if numpy_as_array_works:
metric_xp = metric(a_xp, b_xp, **metric_kwargs)
# Handle cases where multiple return values are not of the same shape,
# e.g. precision_recall_curve:
if (
isinstance(metric_np, tuple)
and len(set([metric_val.shape for metric_val in metric_np])) > 1
):
_check_each_metric_matches(metric_xp, metric_np)
metric_xp_mixed_1 = metric(a_np, b_xp, **metric_kwargs)
_check_each_metric_matches(metric_xp_mixed_1, metric_np)
metric_xp_mixed_2 = metric(a_xp, b_np, **metric_kwargs)
_check_each_metric_matches(metric_xp_mixed_2, metric_np)
else:
_check_metric_matches(metric_xp, metric_np)
metric_xp_mixed_1 = metric(a_np, b_xp, **metric_kwargs)
_check_metric_matches(metric_xp_mixed_1, metric_np)
metric_xp_mixed_2 = metric(a_xp, b_np, **metric_kwargs)
_check_metric_matches(metric_xp_mixed_2, metric_np)

Why is out-of-the-box support of array types on cpu an assumption we can make? Does it also hold on any other function or method without array api support?

If it works it means we've changed something in this PR, such that sample weight is no longer converted to numpy.

True. I will investigate that.

@lucyleeow

Copy link
Copy Markdown
Member

I understand the confusion now. I was also confused, see discussion in #32676.

It seemed that others knew what was going on so I assumed it was just me 😅

@StefanieSenger

Copy link
Copy Markdown
Member Author

I understand the confusion now. I was also confused, see discussion in #32676.

That discussion is very enlightening. I didn't know that "passing a PyTorch cpu tensor has been working for ever" but was undocumented in the past.
So then the test newly added in #30454 is some kind of regression test to make sure the old behaviour (converting to numpy) is still the same after array api support was added. Okay, then I now also understand why you tried to trace a way to check_array on the original PR.

@StefanieSenger

StefanieSenger commented Jan 13, 2026 •

Copy link
Copy Markdown
Member Author

Actually, this test fails on main, too:

import torch
from sklearn import config_context
from sklearn.metrics import average_precision_score

y_score = torch.tensor([[0.1, 0.4, 0.8], [0.1, 0.1, 0.0], [0.1, 0.4, 0.1], [0.7, 0.1, 0.1]], device='cpu')
y_true = torch.tensor([2, 0, 1, 1], device='cpu')
sw = torch.tensor([1, 2, 1, 1], device='cpu')
with config_context(array_api_dispatch=False):
    average_precision_score(y_true, y_score, sample_weight=sw, average="weighted")

In a binary case, we return via precision_recall_curve and thus sample_weight (which is a tensor) never gets called within np.sum or np.repeat. In the other cases, we don't use precision_recall_curve.

@StefanieSenger

Copy link
Copy Markdown
Member Author

So if we assume that torch tensors on cpu had been supported as input on metrics before, this would have been a bug before, but since we didn't document this and nobody reported, maybe not a severe bug.

In #32909, we could call move_to or _convert_to_numpy or check_array on sample_weight to convert it to numpy either in time or in the beginning of the function. What do you think, @lucyleeow?

@github-project-automation github-project-automation Bot moved this to Todo in Labs Jan 13, 2026
@StefanieSenger StefanieSenger moved this from Todo to In progress - High Priority in Labs Jan 13, 2026
@StefanieSenger
StefanieSenger marked this pull request as draft January 13, 2026 13:25
@lucyleeow

Copy link
Copy Markdown
Member

but since we didn't document this and nobody reported, maybe not a severe bug.

AFAICT it seems only when sample_weight is given and average=weighted (?) so maybe it was a case of it affecting few use cases...?

we could call move_to or _convert_to_numpy or check_array on sample_weight to convert it to numpy either in time or in the beginning of the function.

What do 'similar' metrics (with the average parameter) do? Do they also fail...? In which case we may want something that can be applied everywhere...?

@StefanieSenger

Copy link
Copy Markdown
Member Author

AFAICT it seems only when sample_weight is given and average=weighted (?)

Yes, and additionally y_true needs to be multiclass.

What do 'similar' metrics (with the average parameter) do? Do they also fail...? In which case we may want something that can be applied everywhere...?

There is only roc_auc_score that has an average attribute, that is getting used with weights via _multiclass_roc_auc_score and then _binary_roc_auc_score if ovr (calling roc_curve interally, which already has array API support and which passes the test).
These three possibilities (move_to or _convert_to_numpy or check_array) are quite interchangable the the simple case of converting an array, aren't they? I would maybe not use check_array to prevent overhead?

@StefanieSenger

Copy link
Copy Markdown
Member Author

Summary: I would add

    if sample_weight is not None:
        sample_weight = column_or_1d(sample_weight)

which prevents the error from happening on my branch.


More detailed analysis:
I checked how sample_weight gets dealt with in the other ranking metrics and it seems there is no consitent mechanism that makes sure it gets converted to numpy.

In one case (I think) it gets passed through a check_array via column_or_1d(sample_weight).

In the other cases, it just seems to work by coincidence:
coverage_error passes with torch input, even though we don't convert sample_weight to numpy internally:

y_score = torch.tensor([[1, 0, 0], [0, 1, 1]], device='cpu')
y_true = torch.tensor([[1, 0, 0], [0, 1, 1]], device='cpu')
sw = torch.tensor([1, 2], device='cpu')

with config_context(array_api_dispatch=False):
    coverage_error(y_true, y_score, sample_weight=sw) 

return float(np.average(coverage, weights=sample_weight))

gets a torch array for sample_weight and two numpy arrays for y_true and y_score.

Similarly ndcg_score passes with torch input:

y_score = torch.tensor([[1, 0, 0], [0, 1, 1]], device='cpu')
y_true = torch.tensor([[1, 0, 0], [0, 1, 1]], device='cpu')
sw = torch.tensor([1, 2], device='cpu')

with config_context(array_api_dispatch=False):
    ndcg_score(y_true, y_score, sample_weight=sw)

return float(np.average(gain, weights=sample_weight))

gets passed a torch array and can again deal with it. There are 2-3 other places where np.average gets sample_weight that may be torch array.

(There is also a call to _check_sample_weight(sample_weight, y_true) in another case, though it does not do a torch to numpy conversion.)

@lucyleeow

lucyleeow commented Jan 22, 2026 •

Copy link
Copy Markdown
Member

In the other cases, it just seems to work by coincidence:

Interesting. (it seems that the tensor input just seems to work for some np functions but not others). I found some documentation about this here: https://numpy.org/doc/stable/user/basics.interoperability.html, in particular this section: https://numpy.org/devdocs/user/basics.interoperability.html#operating-on-foreign-objects-without-converting

Unfortunately, later on in https://numpy.org/devdocs/user/basics.interoperability.html#example-pytorch-tensors it says:

PyTorch does not implement array_function or array_ufunc. Under the hood, the Tensor.array() method returns a NumPy ndarray as a view of the tensor data buffer.

But digging into the code, at least I found _wrapreduction:

def _wrapreduction(obj, ufunc, method, axis, dtype, out, **kwargs):
    passkwargs = {k: v for k, v in kwargs.items()
                  if v is not np._NoValue}

    if type(obj) is not mu.ndarray:
        try:
            reduction = getattr(obj, method)
        except AttributeError:
            pass
        else:
            # This branch is needed for reductions like any which don't
            # support a dtype.
            if dtype is not None:
                return reduction(axis=axis, dtype=dtype, out=out, **passkwargs)
            else:
                return reduction(axis=axis, out=out, **passkwargs)

    return ufunc.reduce(obj, axis, dtype, out, **passkwargs)

which shows that if the object is not a numpy array, it tries to get the method from the array. I could not find any documentation of this behaviour, and the interoperability page above is a little misleading if anything.

Vaguely useful, but also not clear, there is a list of numpy array methods that also have corresponding numpy functions: https://numpy.org/doc/1.21/reference/arrays.ndarray.html#array-methods - sum and repeat (which you already noted failed) are on here, tried a few, more failed than passed. 🤷

tl;dr - some numpy functions will also have a tensor method, and some of these will work and some of these won't, you won't know until you try? 🤷

FYI mentioned this to Olivier in the array API meeting and he simply suggested that we should improve tests for this but it is not a priority.

@StefanieSenger

Copy link
Copy Markdown
Member Author

Thanks for the deep dive, @lucyleeow!

tried a few, more failed than passed. 🤷
tl;dr - some numpy functions will also have a tensor method, and some of these will work and some of these won't, you won't know until you try? 🤷

That indeed sounds a bit chaotic. Though I think if users don't report a bug around it (this particular one must have existed for years) then it is maybe not a problem. Or the users know their way around by converting torch to numpy beforehand.

Are you fine with this as a solution?

    if sample_weight is not None:
        sample_weight = column_or_1d(sample_weight)

@StefanieSenger StefanieSenger changed the title DEBUG Add array API support for average_precision_score DEBUG torch incompatibility with np.sum and np.repeat (pure debug PR, will be closed soon) Jan 22, 2026
@lucyleeow

Copy link
Copy Markdown
Member

Though I think if users don't report a bug around it (this particular one must have existed for years) then it is maybe not a problem.

Agreed.

I meant to add, for the other metrics that 'just seem to work' (from _ranking.py I noted label_ranking_average_precision_score, coverage_error and label_ranking_loss) - we had decided that it is fine to leave them as is, and not explicitly convert sample_weightto a tensor - as long as we test them - though again this is not a priority.

Are you fine with this as a solution?

Yes! Looking at just the metrics in _ranking.py, most of the ones that explicitly do something with sample_weight call confusion_matrix_at_thresholds, which does column_or_1d so that is pretty consistent with most other metrics.

@StefanieSenger

Copy link
Copy Markdown
Member Author

Thanks for having a closer look at this @lucyleeow.

I think we can now close it. The other metrics that might fail on not converted input types (label_ranking_average_precision_score, coverage_error, label_ranking_loss and maybe more), will be re-discovered when adding array API support to them, since the already existing test will then fail.

@github-project-automation github-project-automation Bot moved this from In progress - High Priority to Done in Labs Jan 23, 2026
@adrinjalali adrinjalali removed this from Labs Mar 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants