Skip to content

FIX ridge validation of alphas with array api - #34004

Merged
betatim merged 9 commits into
scikit-learn:mainfrom
tomMoral:FIX_ridge_multi-alpha_array
May 29, 2026
Merged

betatim merged 9 commits into
scikit-learn:mainfrom
tomMoral:FIX_ridge_multi-alpha_array

Conversation

@tomMoral

@tomMoral tomMoral commented May 12, 2026 •

Copy link
Copy Markdown
Contributor

Fix for #34003

Allows to pass both np.array and an array of the same type as fit data as alphas.
Add non regression tests.

Need to add non-regression tests

@github-actions github-actions Bot added the CI:Linter failure The linter CI is failing on this PR label May 12, 2026
@github-actions github-actions Bot removed the CI:Linter failure The linter CI is failing on this PR label May 12, 2026
@betatim

betatim commented May 19, 2026

Copy link
Copy Markdown
Member

Looks like the failure on macOS is with pytorch MPS because one element of the array is too different. Maybe a precision problem. Running the CUDA tests to see what they say while I think about the macOS failure and the PR.

@jeremiedbb jeremiedbb added this to the 1.9 milestone May 19, 2026
@betatim

betatim commented May 19, 2026

Copy link
Copy Markdown
Member

Thanks for making the PR. I think the only thing we need to discuss is if we want to allow ndarray or not (if X is a torch tensor). Generally we try to go for "everything should be from the same namespace", for example the fitted attributes of an estimator are in the same namespace as X. The idea behind this is trying to have a simple rule and make it predictable what the type of something is or will be.

However, for argument to estimators (like alpha) I feel like it is a good user experience if the user can pass "reasonable things" and we take care of converting them. For example, a strict reading of the above "should match X" rule would mean that when X = torch.tensor(..., device="cuda") the user would also have to construct alpha = torch.asarray(alpha, device="cuda") in order to pass it. This feels super tedious, not user friendly and unclear what the benefit is.

So at the moment I am thinking we should be quite flexible with what we accept for hyper-parameters. For example, we could say that any "array-like" would be fine and take care of the conversion. In some sense that would be consistent with the "everything follows X" principle.

Conclusion: I'd accept this change.

Homework for this PR: make it so that reg = Ridge(alpha=[1.]*10) also works. Because a list is also a array-like and maybe the most(?) convenient way to specify many alphas.

The homework for a new PR: make sure we have a common check that enforces this.

What do the other array API people think? @ogrisel @lucyleeow @virchan

assert_allclose(move_to(pred_xp, xp=np, device="cpu"), pred_np)

# check that passing the same array type for alpha also works as expected
estimator = Ridge(alpha=xp.asarray(alphas), solver="svd")

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.

I would have expected the following:

Suggested change
estimator = Ridge(alpha=xp.asarray(alphas), solver="svd")
estimator = Ridge(alpha=xp.asarray(alphas, device=device), solver="svd")

Using the implicit default device should work on most libraries, but I am not sure if it will continue working in the future for libraries such as array-api-strict.

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.

If we allow "all the array-likes" then it shouldn't matter if you specify a device here or not/what device this is on. Using torch + a device that doesn't match the device of X should work just as well as using a ndarray here.

@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.

Besides the above (and pending the needed test fix for the MPS/float32 device), I am fine with the fix.

Comment thread sklearn/linear_model/_ridge.py Resolved
@lucyleeow

Copy link
Copy Markdown
Member

General question if we are happy for array-like hyperparameters to be converted by the estimator, should we add a common test that checks all 'array-like' inputs are converted...?

@ogrisel

ogrisel commented May 22, 2026

Copy link
Copy Markdown
Member

General question if we are happy for array-like hyperparameters to be converted by the estimator, should we add a common test that checks all 'array-like' inputs are converted...?

That might be a good idea but in practice it might be challenging to find suitable array values in an estimator agnostic manner. Maybe we could inspect the range of valid value expressed in parameters validation constraints, but they might not be specific enough and require setting extra non default hparams.

Alternatively we could specify explicit array hparams values in PER_ESTIMATOR_CHECK_PARAMS using numpy and let the common test for conversion to array API specify using get_params / set_params on a clone.

@lucyleeow

Copy link
Copy Markdown
Member

That's a good point. Do you think we could make some heuristics using the default value? E.g., default value of alpha in Ridge is 1 -> what if checked if the parameter is an array and if not make it an array of e.g., [default value, default value x 2] ?

Comment on lines 703 to 704
# There should be either 1 or n_targets penalties
alpha = _ravel(xp.asarray(alpha, device=device_, dtype=X.dtype), xp=xp)

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.

Here's what happens to alpha in _ridge_regression

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.

For example, we could say that any "array-like" would be fine and take care of the conversion.

@betatim, I agree and it looks like this what's already implemented

@tomMoral

Copy link
Copy Markdown
Contributor Author

Not sure how to handle the mps failure and also note that putting n_features=100 l.1514 also yields a failure with torch cpu backend:

_________________________________________ test_ridge_per_target_alpha_array_api[torch-cpu-float32] _________________________________________

array_namespace = 'torch', device_name = 'cpu', dtype_name = 'float32'

    @pytest.mark.parametrize(
        "array_namespace, device_name, dtype_name",
        yield_namespace_device_dtype_combinations(),
    )
    def test_ridge_per_target_alpha_array_api(array_namespace, device_name, dtype_name):
        # non-regression test for #34003, where passing a array-like for alpha was
        # not working with array API dispatch
        xp, device = _array_api_for_tests(array_namespace, device_name, dtype_name)
        X, y = make_regression(n_targets=3, n_features=100, random_state=0)
        X_np = X.astype(dtype_name)
        y_np = y.astype(dtype_name)
        alphas = np.asarray([1e-2, 0.1, 1.0], dtype=dtype_name)
        estimator = Ridge(alpha=alphas, solver="svd")
    
        ridge_np = estimator.fit(X_np, y_np)
        pred_np = ridge_np.predict(X_np)
        with config_context(array_api_dispatch=True):
            X_xp, y_xp = xp.asarray(X_np, device=device), xp.asarray(y_np, device=device)
    
            # check that passing a numpy array for alpha works as expected
            estimator = Ridge(alpha=alphas, solver="svd")
            ridge_xp = estimator.fit(X_xp, y_xp)
            pred_xp = ridge_xp.predict(X_xp)
            assert pred_xp.shape == pred_np.shape == y.shape
>           assert_allclose(move_to(pred_xp, xp=np, device="cpu"), pred_np)

sklearn/linear_model/tests/test_ridge.py:1530: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

actual = array([[ 8.97728577e+01,  8.07121582e+01, -6.99864044e+01],
       [-2.06915024e+02, -3.41886566e+02, -2.91464203e+02]...876e+01, -7.56005325e+01, -1.04415405e+02],
       [ 2.14425491e+02,  9.88522263e+01,  2.31183105e+02]], dtype=float32)
desired = array([[ 8.97727127e+01,  8.07121582e+01, -6.99864273e+01],
       [-2.06914932e+02, -3.41886475e+02, -2.91464264e+02]...549e+01, -7.56003265e+01, -1.04415276e+02],
       [ 2.14425369e+02,  9.88519516e+01,  2.31182877e+02]], dtype=float32)
rtol = 0.0001, atol = 0.0, equal_nan = True, err_msg = '', verbose = True

    def assert_allclose(
        actual, desired, rtol=None, atol=0.0, equal_nan=True, err_msg="", verbose=True
    ):
        """dtype-aware variant of numpy.testing.assert_allclose
    
        This variant introspects the least precise floating point dtype
        in the input argument and automatically sets the relative tolerance
        parameter to 1e-4 float32 and use 1e-7 otherwise (typically float64
        in scikit-learn).
    
        `atol` is always left to 0. by default. It should be adjusted manually
        to an assertion-specific value in case there are null values expected
        in `desired`.
    
        The aggregate tolerance is `atol + rtol * abs(desired)`.
    
        Parameters
        ----------
        actual : array_like
            Array obtained.
        desired : array_like
            Array desired.
        rtol : float, optional, default=None
            Relative tolerance.
            If None, it is set based on the provided arrays' dtypes.
        atol : float, optional, default=0.
            Absolute tolerance.
        equal_nan : bool, optional, default=True
            If True, NaNs will compare equal.
        err_msg : str, optional, default=''
            The error message to be printed in case of failure.
        verbose : bool, optional, default=True
            If True, the conflicting values are appended to the error message.
    
        Raises
        ------
        AssertionError
            If actual and desired are not equal up to specified precision.
    
        See Also
        --------
        numpy.testing.assert_allclose
    
        Examples
        --------
        >>> import numpy as np
        >>> from sklearn.utils._testing import assert_allclose
        >>> x = [1e-5, 1e-3, 1e-1]
        >>> y = np.arccos(np.cos(x))
        >>> assert_allclose(x, y, rtol=1e-5, atol=0)
        >>> a = np.full(shape=10, fill_value=1e-5, dtype=np.float32)
        >>> assert_allclose(a, 1e-5)
        """
        dtypes = []
    
        actual, desired = np.asanyarray(actual), np.asanyarray(desired)
        dtypes = [actual.dtype, desired.dtype]
    
        if rtol is None:
            rtols = [1e-4 if dtype == np.float32 else 1e-7 for dtype in dtypes]
            rtol = max(rtols)
    
>       np_assert_allclose(
            actual,
            desired,
            rtol=rtol,
            atol=atol,
            equal_nan=equal_nan,
            err_msg=err_msg,
            verbose=verbose,
        )
E       AssertionError: 
E       Not equal to tolerance rtol=0.0001, atol=0
E       
E       Mismatched elements: 3 / 300 (1%)
E       Max absolute difference among violations: 0.00036526
E       Max relative difference among violations: 0.00071551
E        ACTUAL: array([[ 8.977286e+01,  8.071216e+01, -6.998640e+01],
E              [-2.069150e+02, -3.418866e+02, -2.914642e+02],
E              [ 1.699422e+02,  1.885383e+02,  8.361436e+01],...
E        DESIRED: array([[ 8.977271e+01,  8.071216e+01, -6.998643e+01],
E              [-2.069149e+02, -3.418865e+02, -2.914643e+02],
E              [ 1.699422e+02,  1.885384e+02,  8.361426e+01],...

sklearn/utils/_testing.py:236: AssertionError
========================================================= short test summary info ==========================================================
FAILED sklearn/linear_model/tests/test_ridge.py::test_ridge_per_target_alpha_array_api[torch-cpu-float32] - AssertionError: 

As I am not clear on what's the expected violation/policy, happy to invesigate with a few rules in mind.

@betatim

betatim commented May 27, 2026 •

Copy link
Copy Markdown
Member

I think the assert_allclose comparison should use atol=_atol_for_type(dtype_name) to get a type specific tolerance. I'd look at check_array_api_attributes in sklearn/linear_models/tests/test_ridge.py for inspiration/details

@github-actions github-actions Bot removed the CUDA CI label May 27, 2026

@jeremiedbb jeremiedbb 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.

All green now. LGTM, thanks.

@betatim betatim 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.

Thanks everyone!

@betatim
betatim merged commit dd3a56e into scikit-learn:main May 29, 2026
38 checks passed
@tomMoral
tomMoral deleted the FIX_ridge_multi-alpha_array branch May 30, 2026 06:04
@tomMoral

Copy link
Copy Markdown
Contributor Author

Thanks a lot for fixing the tests !
I got confused with rtol that was already adapted to dtype automatically.

@jeremiedbb jeremiedbb mentioned this pull request Jun 1, 2026
16 tasks done
jeremiedbb added a commit that referenced this pull request Jun 2, 2026
prady0t pushed a commit to prady0t/scikit-learn that referenced this pull request Sep 2, 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