Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 27 additions & 32 deletions python/cuml/cuml/random_projection/random_projection.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,18 @@
# SPDX-FileCopyrightText: Copyright (c) 2025-2026, NVIDIA CORPORATION.
# SPDX-License-Identifier: Apache-2.0
import cupy as cp
import cupyx.scipy.sparse as cp_sp
import cupyx.scipy.sparse as sp
import numpy as np
import scipy.sparse as sp

from cuml.common.array_descriptor import CumlArrayDescriptor
from cuml.common.doc_utils import generate_docstring
from cuml.internals.array import CumlArray
from cuml.internals.array_sparse import SparseCumlArray
from cuml.internals.base import Base
from cuml.internals.input_utils import input_to_cuml_array
from cuml.internals.mixins import SparseInputTagMixin
from cuml.internals.outputs import reflect
from cuml.internals.validation import (
check_features,
check_inputs,
check_is_fitted,
check_random_seed,
)
Expand Down Expand Up @@ -82,19 +80,24 @@ def _gen_random_matrix(self, n_components, n_features, dtype):
raise NotImplementedError

@generate_docstring()
@reflect(reset=True)
@reflect(reset="type")
def fit(self, X, y=None, *, convert_dtype=True):
"""Generate a random projection matrix."""
# Use `mem_type=None` & `order=None` to minimize copies or transfers. We
# don't need to access the data here, just ensure it's valid and get
# the shape/dtype
X = check_inputs(
self,
X,
dtype=("float32", "float64"),
convert_dtype=convert_dtype,
Comment thread
jcrist marked this conversation as resolved.
Resolved
mem_type=None,
order=None,
accept_sparse=True,
reset=True,
Comment thread
jcrist marked this conversation as resolved.
Resolved
)
Comment thread
jcrist marked this conversation as resolved.
Resolved
n_samples, n_features = X.shape

# Prefer float32, unless `convert_dtype=False` and the input is float64
if convert_dtype:
dtype = np.float32
else:
dtype = getattr(X, "dtype", np.float32)
if dtype not in ("float32", "float64"):
dtype = np.float32

if self.n_components == "auto":
self.n_components_ = johnson_lindenstrauss_min_dim(
n_samples=n_samples, eps=self.eps
Expand All @@ -114,7 +117,7 @@ def fit(self, X, y=None, *, convert_dtype=True):
)

self.components_ = self._gen_random_matrix(
self.n_components_, n_features, dtype
self.n_components_, n_features, X.dtype
)

return self
Expand All @@ -124,22 +127,14 @@ def fit(self, X, y=None, *, convert_dtype=True):
def transform(self, X, *, convert_dtype=True) -> CumlArray:
"""Project the data by taking the matrix product with the random matrix."""
check_is_fitted(self)
check_features(self, X)

# Coerce X to a cupy array or cupyx sparse matrix
index = None
if sp.issparse(X):
X = cp_sp.csr_matrix(X)
elif not cp_sp.issparse(X):
X_m = input_to_cuml_array(
X,
convert_to_dtype=(np.float32 if convert_dtype else None),
check_dtype=[np.float32, np.float64],
order="K",
).array
index = X_m.index
X = X_m.to_output("cupy")

X, index = check_inputs(
self,
X,
dtype=("float32", "float64"),
convert_dtype=convert_dtype,
accept_sparse=("csr", "csc"),
return_index=True,
)
components = self.components_.to_output("cupy")

# Compute the output
Expand All @@ -150,7 +145,7 @@ def transform(self, X, *, convert_dtype=True) -> CumlArray:
if out.dtype != self.components_.dtype:
out = out.astype(self.components_.dtype)

if sp.issparse(out) or cp_sp.issparse(out):
if sp.issparse(out):
if not getattr(self, "dense_output", False):
# Sparse output
return out
Expand Down Expand Up @@ -423,7 +418,7 @@ def _gen_random_matrix(self, n_components, n_features, dtype):
data = cp.multiply(data, factor, dtype=dtype)

return SparseCumlArray(
data=cp_sp.coo_matrix(
data=sp.coo_matrix(
(data, (i, j)), shape=(n_components, n_features)
).asformat("csr")
)
17 changes: 4 additions & 13 deletions python/cuml/tests/test_random_projection.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# SPDX-FileCopyrightText: Copyright (c) 2018-2025, NVIDIA CORPORATION.
# SPDX-FileCopyrightText: Copyright (c) 2018-2026, NVIDIA CORPORATION.
# SPDX-License-Identifier: Apache-2.0
import cupy as cp
import cupyx.scipy.sparse as cp_sp
Expand Down Expand Up @@ -169,21 +169,12 @@ def test_random_seed_consistency(cls, sparse):

@pytest.mark.parametrize("cls", classes)
@pytest.mark.parametrize("dtype", ["float32", "float64"])
def test_components_dtype(cls, dtype):
def test_components_and_output_dtype(cls, dtype):

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.

This test and behavior was incorrect and doesn't match our intended behavior of convert_dtype. I view the change here as a bugfix. Also note that I wrote the code (and test) a few months ago, so I know this wasn't intentional for a specific user need, just a buggy implementation of a standard kwarg.

X = random_array(10, 100, dtype=dtype)

# float32 used by default for all inputs
model = cls(random_state=42, n_components=5)
transformed = model.fit_transform(X)
assert model.components_.dtype == "float32"
assert transformed.dtype == "float32"

# float64 available if `convert_dtype=False` and float64
expected = "float64" if dtype == "float64" else "float32"
model = cls(random_state=42, n_components=5)
transformed = model.fit_transform(X, convert_dtype=False)
assert model.components_.dtype == expected
assert transformed.dtype == expected
assert model.components_.dtype == dtype
assert transformed.dtype == dtype
Comment thread
jcrist marked this conversation as resolved.
Resolved


@pytest.mark.parametrize("cls", classes)
Expand Down
8 changes: 0 additions & 8 deletions python/cuml/tests/test_sklearn_compatibility.py
Original file line number Diff line number Diff line change
Expand Up @@ -364,18 +364,10 @@
},
GaussianRandomProjection: {
"check_estimator_tags_renamed": "No support for modern tags infrastructure",
"check_complex_data": "GaussianRandomProjection doesn't support complex data",
"check_dtype_object": "GaussianRandomProjection doesn't support dtype object",
"check_estimators_empty_data_messages": "GaussianRandomProjection doesn't check for empty data",
"check_estimators_nan_inf": "GaussianRandomProjection does not check for NaN and inf",
"check_transformer_data_not_an_array": "GaussianRandomProjection does not handle non-array data",
},
SparseRandomProjection: {
"check_estimator_tags_renamed": "No support for modern tags infrastructure",
"check_complex_data": "SparseRandomProjection doesn't support complex data",
"check_dtype_object": "SparseRandomProjection doesn't support dtype object",
"check_estimators_empty_data_messages": "SparseRandomProjection doesn't check for empty data",
"check_estimators_nan_inf": "SparseRandomProjection does not check for NaN and inf",
"check_transformer_data_not_an_array": "SparseRandomProjection does not handle non-array data",
},
BernoulliNB: {
Expand Down
Loading