Skip to content
Closed
61 changes: 1 addition & 60 deletions python/cuml/cuml/accel/_overrides/sklearn/preprocessing.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,72 +3,13 @@
# SPDX-License-Identifier: Apache-2.0
#

import cupyx.scipy.sparse as cupy_sparse
import numpy as np
from scipy import sparse as sp_sparse

import cuml.preprocessing
from cuml.accel.estimator_proxy import ProxyBase
from cuml.internals.interop import UnsupportedOnGPU

__all__ = ("StandardScaler", "TargetEncoder")


def _check_standardscaler_unsupported_inputs(X, **kwargs):
"""Check if inputs are supported by cuML's StandardScaler on GPU.

Raises UnsupportedOnGPU for unsupported cases to trigger CPU fallback.
"""
if kwargs.get("sample_weight") is not None:
raise UnsupportedOnGPU("sample_weight is not supported")

# Reject complex, object, and float16 dtypes
if hasattr(X, "dtype"):
if np.issubdtype(X.dtype, np.complexfloating):
raise UnsupportedOnGPU("complex dtype is not supported")
if X.dtype == np.object_:
raise UnsupportedOnGPU("object dtype is not supported")
if X.dtype == np.float16:
raise UnsupportedOnGPU("float16 dtype is not supported")

# Check for sparse matrices with unsupported properties
if sp_sparse.issparse(X):
if np.issubdtype(X.dtype, np.integer):
raise UnsupportedOnGPU(
"sparse matrix with integer dtype is not supported"
)
# cuML's StandardScaler algorithm only supports CSR/CSC formats.
if X.format not in ("csr", "csc"):
raise UnsupportedOnGPU(
f"sparse matrix format '{X.format}' is not supported"
)
elif cupy_sparse.issparse(X):
if np.issubdtype(X.dtype, np.integer):
raise UnsupportedOnGPU(
"sparse matrix with integer dtype is not supported"
)
# cuML's StandardScaler algorithm only supports CSR/CSC formats.
if X.format not in ("csr", "csc"):
raise UnsupportedOnGPU(
f"sparse matrix format '{X.format}' is not supported"
)


class StandardScaler(ProxyBase):
_gpu_class = cuml.preprocessing.StandardScaler

def _gpu_fit(self, X, y=None, sample_weight=None):
kwargs = {"sample_weight": sample_weight}
_check_standardscaler_unsupported_inputs(X, **kwargs)
return self._gpu.fit(X, y)

def _gpu_fit_transform(self, X, y=None, **fit_params):
_check_standardscaler_unsupported_inputs(X, **fit_params)
return self._gpu.fit_transform(X, y, **fit_params)

def _gpu_partial_fit(self, X, y=None, sample_weight=None):
"""partial_fit not supported on GPU - always fall back to CPU."""
raise UnsupportedOnGPU("partial_fit not supported on GPU")
__all__ = ("TargetEncoder",)


def _check_unsupported_inputs(X, y, cpu_model):
Expand Down
37 changes: 37 additions & 0 deletions python/cuml/cuml/accel/_patches/sklearn/_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION.
# SPDX-License-Identifier: Apache-2.0
"""Shared utilities for sklearn patch modules."""

import contextlib
import os

import scipy._lib._array_api as _scipy_array_api


@contextlib.contextmanager
def enable_scipy_array_api():
"""Enable scipy's array API support for the duration of a block.

Sets the SCIPY_ARRAY_API env var (checked by sklearn's config validation)
and updates scipy's cached config (in case scipy had already been
imported). Both are restored on exit.

This is required before entering
``sklearn.config_context(array_api_dispatch=True)`` so that sklearn does
not raise a RuntimeError about scipy's array API support being absent.
"""
old_env = os.environ.get("SCIPY_ARRAY_API")
os.environ["SCIPY_ARRAY_API"] = "1"

old_cached = _scipy_array_api._GLOBAL_CONFIG["SCIPY_ARRAY_API"]
_scipy_array_api._GLOBAL_CONFIG["SCIPY_ARRAY_API"] = "1"

try:
yield
finally:
if old_env is None:
os.environ.pop("SCIPY_ARRAY_API", None)
else:
os.environ["SCIPY_ARRAY_API"] = old_env

_scipy_array_api._GLOBAL_CONFIG["SCIPY_ARRAY_API"] = old_cached
6 changes: 3 additions & 3 deletions python/cuml/cuml/accel/_patches/sklearn/pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from sklearn.pipeline import Pipeline
from sklearn.utils.metaestimators import available_if

from cuml.accel.estimator_proxy import is_proxy
from cuml.accel.estimator_proxy import supports_device_data
from cuml.internals.global_settings import GlobalSettings
from cuml.internals.outputs import using_output_type

Expand Down Expand Up @@ -40,15 +40,15 @@ def flat_steps(pipeline):

# Skip over any non-cupy producing steps
for step in step_iter:
if is_proxy(step):
if supports_device_data(step):
break
else:
# No steps produce cupy
return "numpy"

# If any remaining steps don't consume cupy, we need to fallback to numpy
for step in step_iter:
if not is_proxy(step):
if not supports_device_data(step):
return "numpy"
# Tail of the pipeline supports cupy, we can use cupy
return "cupy"
Expand Down
Loading
Loading