diff --git a/python/cuml/cuml/benchmark/backends/base.py b/python/cuml/cuml/benchmark/backends/base.py index dece2f6c3d..9e98db05ea 100644 --- a/python/cuml/cuml/benchmark/backends/base.py +++ b/python/cuml/cuml/benchmark/backends/base.py @@ -10,13 +10,16 @@ import importlib.metadata from collections.abc import Iterable from dataclasses import dataclass, field -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, Literal from .._utils import _version if TYPE_CHECKING: from ..providers.base import EstimatorSpec - from ..suite import ResolvedCase, Suite + from ..suite import Suite + + +InputRepresentation = Literal["array", "csr", "dataframe", "series"] @dataclass @@ -92,20 +95,33 @@ def effective_parameters(self, estimator: Any) -> dict[str, Any]: return estimator.get_params(deep=False) def convert_data( - self, case: ResolvedCase, X: Any, y: Any - ) -> tuple[Any, Any]: - """Convert generated inputs to the backend's data representation. + self, + value: Any, + *, + representation: InputRepresentation, + ) -> Any: + """Convert a value to the requested backend-native representation. + + Preserve the input dtype and row order. Parameters ---------- - case : ResolvedCase - Case defining the input representation. - X : Any - Complete generated feature data. - y : Any - Complete generated target data. + value : Any + Input data to convert. + representation : {"array", "csr", "dataframe", "series"} + Target data representation. """ - return X, y + if representation == "array": + return importlib.import_module("numpy").asarray(value) + if representation == "csr": + return importlib.import_module("scipy.sparse").csr_matrix(value) + if representation == "dataframe": + return importlib.import_module("pandas").DataFrame(value) + if representation == "series": + return importlib.import_module("pandas").Series(value) + raise ValueError( + f"Unsupported input representation {representation!r}" + ) def prepare_inputs( self, inputs: tuple[Any, ...], runtime: Any = None diff --git a/python/cuml/cuml/benchmark/backends/cuml.py b/python/cuml/cuml/benchmark/backends/cuml.py index 9f78c8cc54..dc87ad8aca 100644 --- a/python/cuml/cuml/benchmark/backends/cuml.py +++ b/python/cuml/cuml/benchmark/backends/cuml.py @@ -13,9 +13,9 @@ from typing import TYPE_CHECKING, Any if TYPE_CHECKING: - from ..suite import ResolvedCase, Suite + from ..suite import Suite -from .base import GPUBackend, VerificationResult +from .base import Backend, GPUBackend, InputRepresentation, VerificationResult def _git_output(root: Path, *args: str) -> str: @@ -125,17 +125,27 @@ def construct_estimator( return estimator def convert_data( - self, case: ResolvedCase, X: Any, y: Any - ) -> tuple[Any, Any]: - """Move generated dense, CSR, or categorical inputs onto the device.""" - cp = importlib.import_module("cupy") - if case.input_format == "csr": - X = importlib.import_module("cupyx.scipy.sparse").csr_matrix(X) - elif case.dataset == "categorical": - X = importlib.import_module("cudf").from_pandas(X) - else: - X = cp.asarray(X) - return X, cp.asarray(y) + self, + value: Any, + *, + representation: InputRepresentation, + ) -> Any: + """Convert a structural representation to device storage.""" + if representation == "array": + return importlib.import_module("cupy").asarray(value) + if representation == "csr": + host = Backend.convert_data(self, value, representation="csr") + return importlib.import_module("cupyx.scipy.sparse").csr_matrix( + host + ) + if representation in {"dataframe", "series"}: + host = Backend.convert_data( + self, value, representation=representation + ) + return importlib.import_module("cudf").from_pandas(host) + raise ValueError( + f"Unsupported input representation {representation!r}" + ) def prepare_inputs( self, inputs: tuple[Any, ...], runtime: Any = None diff --git a/python/cuml/cuml/benchmark/backends/dask.py b/python/cuml/cuml/benchmark/backends/dask.py index 733d7374f0..fac8e6b0a6 100644 --- a/python/cuml/cuml/benchmark/backends/dask.py +++ b/python/cuml/cuml/benchmark/backends/dask.py @@ -11,9 +11,10 @@ from typing import TYPE_CHECKING, Any if TYPE_CHECKING: - from ..suite import ResolvedCase, Suite + from ..suite import Suite -from .cuml import CumlBackend +from .base import InputRepresentation +from .cuml import CumlBackend, NativeCumlBackend def _wait_for_futures(distributed: Any, value: Any) -> None: @@ -31,48 +32,32 @@ class DaskBackend(CumlBackend): """Provide distributed inputs, estimators, and a multi-GPU runtime.""" def convert_data( - self, case: ResolvedCase, X: Any, y: Any - ) -> tuple[Any, Any]: - """Convert generated inputs to partitioned Dask collections. - - Parameters - ---------- - case : ResolvedCase - Case defining the dataset shape and representation. - X : Any - Complete generated feature data. - y : Any - Complete generated target data. - """ - # Distributed DBSCAN broadcasts a complete local array itself; it - # does not accept partitioned Dask collections. - if case.estimator == "DBSCAN": - return X, y - da = importlib.import_module("dask.array") - cp = importlib.import_module("cupy") - # TODO: Split training and inference data before backend conversion, - # then partition and distribute each using the runtime worker count. - # Fixed two-way chunking leaves every built-in inference input in one - # partition, so partition-parallel predictions use only one worker. - # Training also underutilizes clusters with more than two workers. - chunks = (max(1, case.generated_rows // 2), case.features) - if case.dataset == "categorical": - cudf = importlib.import_module("cudf") - dask_cudf = importlib.import_module("dask_cudf") - X = dask_cudf.from_cudf(cudf.from_pandas(X), npartitions=2) - else: - X = da.from_array(X, chunks=chunks).map_blocks( - cp.asarray, meta=cp.empty((0, 0), dtype=X.dtype) + self, + value: Any, + *, + representation: InputRepresentation, + ) -> Any: + """Convert one structural representation to distributed device storage.""" + if representation == "csr": + raise ValueError("Dask CSR inputs are not supported yet") + if representation in {"dataframe", "series"}: + local = NativeCumlBackend.convert_data( + self, value, representation=representation + ) + return importlib.import_module("dask_cudf").from_cudf( + local, npartitions=2 ) - if case.estimator == "LabelEncoder": - cudf = importlib.import_module("cudf") - dask_cudf = importlib.import_module("dask_cudf") - y = dask_cudf.from_cudf(cudf.Series(y), npartitions=2) - else: - y = da.from_array(y, chunks=(chunks[0],)).map_blocks( - cp.asarray, meta=cp.empty((0,), dtype=y.dtype) + if representation != "array": + raise ValueError( + f"Unsupported input representation {representation!r}" ) - return X, y + da = importlib.import_module("dask.array") + cp = importlib.import_module("cupy") + # TODO: Use the runtime worker count instead of fixed two-way chunking. + chunks = (max(1, value.shape[0] // 2), *value.shape[1:]) + return da.from_array(value, chunks=chunks).map_blocks( + cp.asarray, meta=cp.empty((0,) * value.ndim, dtype=value.dtype) + ) def prepare_inputs( self, inputs: tuple[Any, ...], runtime: Any = None diff --git a/python/cuml/cuml/benchmark/harness.py b/python/cuml/cuml/benchmark/harness.py index 5eb0a47938..4d056813b8 100644 --- a/python/cuml/cuml/benchmark/harness.py +++ b/python/cuml/cuml/benchmark/harness.py @@ -86,33 +86,6 @@ def _run_record(suite: Suite, argv: list[str]) -> dict[str, Any]: } -def _generate_data(case: ResolvedCase, backend: Backend) -> tuple[Any, Any]: - """Generate case inputs and convert them for the backend.""" - X, y = generate_data(case) - return backend.convert_data(case, X, y) - - -def _partition_data( - case: ResolvedCase, backend: Backend -) -> tuple[Any, Any, Any, Any]: - """Partition generated inputs into training and measurement data.""" - # TODO: Split host inputs before backend conversion, or provide a backend - # row-slicing hook. Dask-cuDF does not support these positional slices, - # so categorical inference fails even when only y is selected. - X, y = _generate_data(case, backend) - if case.lifecycle == "fit": - return None, None, X, y - split = case.training_rows - return X[:split], y[:split], X[split:], y[split:] - - -def _inputs( - selection: tuple[str, ...], inputs: dict[str, Any] -) -> tuple[Any, ...]: - """Select ordered estimator arguments from named inputs.""" - return tuple(inputs[name] for name in selection) - - def _base_result( suite: Suite, case: ResolvedCase, @@ -160,23 +133,50 @@ def _prepare_case( spec: EstimatorSpec, client: Any = None, ) -> _PreparedCase: - """Load the estimator class and prepare partitioned case inputs.""" + """Partition host data, then convert and materialize only required inputs.""" estimator_class = backend.load_estimator(spec) - X_train, y_train, X, y = _partition_data(case, backend) - operation_args = _inputs(case.input_selection, {"X": X, "y": y}) - fit_args = ( - () - if case.lifecycle == "fit" - else _inputs(case.fit_input_selection, {"X": X_train, "y": y_train}) + provider = suite.provider_spec + + # Generate and partition host data. + X, y = generate_data(case) + is_fit = case.lifecycle == "fit" + if is_fit: + measured = {"X": X, "y": y} + else: + split = case.training_rows + train = {"X": X[:split], "y": y[:split]} + measured = {"X": X[split:], "y": y[split:]} + + # Convert only selected inputs, applying provider-specific requirements. + x_representation = ( + "csr" + if case.input_format == "csr" + else "dataframe" + if case.dataset == "categorical" + else "array" ) - # Keep materialized inputs alive in the prepared case across every warmup - # and measurement, rather than rerunning a lazy conversion graph. - prepared_inputs = backend.prepare_inputs(operation_args + fit_args, client) - split = len(operation_args) + + def convert(inputs, selection): + return tuple( + provider.convert_data( + inputs[name], + estimator=case.estimator, + role=name, + representation=x_representation if name == "X" else "array", + ) + for name in selection + ) + + operation_args = convert(measured, case.input_selection) + fit_args = () if is_fit else convert(train, case.fit_input_selection) + + # Materialize both groups together, then restore their boundary. + prepared = backend.prepare_inputs(operation_args + fit_args, client) + boundary = len(operation_args) return _PreparedCase( estimator_class=estimator_class, - operation_args=prepared_inputs[:split], - fit_args=None if case.lifecycle == "fit" else prepared_inputs[split:], + operation_args=prepared[:boundary], + fit_args=None if is_fit else prepared[boundary:], ) diff --git a/python/cuml/cuml/benchmark/providers/base.py b/python/cuml/cuml/benchmark/providers/base.py index 7eeaa72228..c41e68ce3e 100644 --- a/python/cuml/cuml/benchmark/providers/base.py +++ b/python/cuml/cuml/benchmark/providers/base.py @@ -7,10 +7,10 @@ from collections.abc import Mapping from dataclasses import dataclass -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any, Literal if TYPE_CHECKING: - from ..backends.base import Backend + from ..backends.base import Backend, InputRepresentation @dataclass(frozen=True) @@ -29,6 +29,29 @@ class Provider: backend: Backend catalog: Mapping[str, EstimatorSpec] + def convert_data( + self, + value: Any, + *, + estimator: str, + role: Literal["X", "y"], + representation: InputRepresentation, + ) -> Any: + """Convert a selected input for the provider's estimator. + + Parameters + ---------- + value : Any + Host input data for the selected training or measurement partition. + estimator : str + Estimator name. + role : {"X", "y"} + Feature or target input. + representation : {"array", "csr", "dataframe", "series"} + Requested data representation. + """ + return self.backend.convert_data(value, representation=representation) + def estimator_spec(self, estimator: str) -> EstimatorSpec: """Resolve an estimator within this provider's catalog.""" try: diff --git a/python/cuml/cuml/benchmark/providers/dask.py b/python/cuml/cuml/benchmark/providers/dask.py index f50a6df6cb..ac12604722 100644 --- a/python/cuml/cuml/benchmark/providers/dask.py +++ b/python/cuml/cuml/benchmark/providers/dask.py @@ -3,9 +3,16 @@ """Define the provider for distributed cuML estimators.""" +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal + from ..backends import get_backend from .base import EstimatorSpec, Provider +if TYPE_CHECKING: + from ..backends.base import InputRepresentation + CATALOG = { "KMeans": EstimatorSpec("cuml.dask.cluster", "KMeans", "cuml"), "DBSCAN": EstimatorSpec("cuml.dask.cluster", "DBSCAN", "cuml"), @@ -49,11 +56,38 @@ "cuml.dask.preprocessing", "OrdinalEncoder", "cuml" ), "LabelEncoder": EstimatorSpec( - "cuml.dask.preprocessing", "LabelEncoder", "cuml" + "cuml.dask.preprocessing", + "LabelEncoder", + "cuml", ), "LabelBinarizer": EstimatorSpec( "cuml.dask.preprocessing", "LabelBinarizer", "cuml" ), } -PROVIDER = Provider(get_backend("cuml.dask"), CATALOG) + +class DaskProvider(Provider): + """Adapt inputs to distributed estimators' individual requirements.""" + + def convert_data( + self, + value: Any, + *, + estimator: str, + role: Literal["X", "y"], + representation: InputRepresentation, + ) -> Any: + if estimator == "DBSCAN": + # Distributed DBSCAN accepts local inputs, not Dask collections. + return value + if estimator == "LabelEncoder" and role == "y": + representation = "series" + return super().convert_data( + value, + estimator=estimator, + role=role, + representation=representation, + ) + + +PROVIDER = DaskProvider(get_backend("cuml.dask"), CATALOG) diff --git a/python/cuml/tests/test_benchmark.py b/python/cuml/tests/test_benchmark.py index 2a2b231754..5b1f36ff4f 100644 --- a/python/cuml/tests/test_benchmark.py +++ b/python/cuml/tests/test_benchmark.py @@ -952,7 +952,7 @@ def test_estimator_lifecycle_and_inputs( case = resolve_case(request, {**PROFILE, "warmups": warmups}) X = np.arange(case.generated_rows * 8).reshape(-1, 8) y = np.arange(case.generated_rows) - monkeypatch.setattr(harness, "_generate_data", lambda *args: (X, y)) + monkeypatch.setattr(harness, "generate_data", lambda *args: (X, y)) instances, calls = [], [] class Estimator: @@ -1031,7 +1031,7 @@ def predict(self, *args): def score(self, *args): pytest.fail("must not score during benchmarking") - def generate(case, provider): + def generate(case): events.append("generate") return np.ones((case.generated_rows, case.features)), np.zeros( case.generated_rows @@ -1039,7 +1039,7 @@ def generate(case, provider): backend = get_backend("cpu") monkeypatch.setattr(backend, "load_estimator", lambda spec: Estimator) - monkeypatch.setattr(harness, "_generate_data", generate) + monkeypatch.setattr(harness, "generate_data", generate) monkeypatch.setattr( backend, "synchronize", @@ -1101,12 +1101,13 @@ def synchronize(): monkeypatch.setattr(backend, "load_estimator", lambda spec: Estimator) monkeypatch.setattr( harness, - "_generate_data", - lambda case, backend: (np.ones((64, 8)), None), + "generate_data", + lambda case: (np.ones((64, 8)), None), ) monkeypatch.setattr( backend, "prepare_inputs", lambda inputs, runtime: inputs ) + monkeypatch.setattr(backend, "convert_data", lambda value, **kwargs: value) monkeypatch.setattr( backend, "instrumentation", @@ -2250,7 +2251,15 @@ def test_native_device_preparation_and_output_contract(kind): request["dataset"]["format"] = "csr" case = resolve_case(request, PROFILE) X_host, y_host = generate_data(case) - X, y = backend.convert_data(case, X_host, y_host) + X = backend.convert_data( + X_host, + representation="csr" + if kind == "csr" + else "dataframe" + if kind == "categorical" + else "array", + ) + y = backend.convert_data(y_host, representation="array") assert isinstance(y, cp.ndarray) if kind == "categorical": assert isinstance(X, cudf.DataFrame) @@ -2308,12 +2317,11 @@ def predict(self, X): events.append("predict") return X - def partition(case, selected_backend): - assert selected_backend is backend + def convert(value, *, representation): events.append("convert") - return X_device, y_device, X_device, y_device + return X_device if value.ndim == 2 else y_device - monkeypatch.setattr(harness, "_partition_data", partition) + monkeypatch.setattr(backend, "convert_data", convert) monkeypatch.setattr(backend, "load_estimator", lambda spec: Estimator) monkeypatch.setattr( backend, "synchronize", lambda value=None: events.append("sync") @@ -2327,7 +2335,15 @@ def partition(case, selected_backend): assert result["outcome"] == {"status": "success"} assert ( events - == ["convert", "sync", "construct", "fit", "sync"] + == [ + "convert", + "convert", + "convert", + "sync", + "construct", + "fit", + "sync", + ] + ["sync", "clock", "predict", "sync", "clock"] * 3 ) @@ -2387,8 +2403,9 @@ def persist(self, values): monkeypatch.setattr(backend, "load_estimator", lambda spec: Estimator) monkeypatch.setattr(backend, "synchronize", lambda value=None: None) monkeypatch.setattr( - harness, "_generate_data", lambda *args: (Input("X"), Input("y")) + harness, "generate_data", lambda *args: (Input("X"), Input("y")) ) + monkeypatch.setattr(backend, "convert_data", lambda value, **kwargs: value) request = _request() if inference: request.update(operation="predict", fit_input_selection=["X", "y"]) @@ -2544,11 +2561,14 @@ def test_dask_synchronization_propagates_failure( def test_dask_input_conversion(estimator): cp = pytest.importorskip("cupy") pytest.importorskip("dask_cudf") - case = resolve_case(_request(estimator=estimator), PROFILE) X = np.arange(512, dtype=np.float32).reshape(64, 8) y = np.arange(64, dtype=np.int64) % 3 - converted_X, converted_y = get_backend("cuml.dask").convert_data( - case, X, y + provider = get_provider("cuml.dask") + converted_X = provider.convert_data( + X, estimator=estimator, role="X", representation="array" + ) + converted_y = provider.convert_data( + y, estimator=estimator, role="y", representation="array" ) assert isinstance(converted_X._meta, cp.ndarray) cp.testing.assert_array_equal(converted_X.compute(), cp.asarray(X)) @@ -2588,15 +2608,28 @@ def get_params(self, deep=False): assert result["parameters"]["effective"] == expected -def test_dask_dbscan_uses_local_input(): +def test_dask_dbscan_uses_local_input(monkeypatch): case = resolve_case(_request(estimator="DBSCAN"), PROFILE) X = np.zeros((64, 8), dtype=np.float32) y = np.zeros(64, dtype=np.int64) - converted_X, converted_y = get_backend("cuml.dask").convert_data( - case, X, y + spec = get_provider("cuml.dask").estimator_spec(case.estimator) + backend = get_backend("cuml.dask") + monkeypatch.setattr(harness, "generate_data", lambda case: (X, y)) + monkeypatch.setattr( + backend, + "convert_data", + lambda *args, **kwargs: pytest.fail( + "host inputs must bypass conversion" + ), ) - assert converted_X is X - assert converted_y is y + monkeypatch.setattr( + backend, "prepare_inputs", lambda inputs, client: inputs + ) + monkeypatch.setattr(backend, "load_estimator", lambda spec: object) + prepared = harness._prepare_case( + backend, _suite(case, provider="cuml.dask"), case, spec + ) + assert prepared.operation_args[0] is X @pytest.mark.parametrize("count", [0, 1]) @@ -3097,3 +3130,111 @@ def execute(command, environment): assert all( process.status() == psutil.STATUS_ZOMBIE for process in alive ) + + +@pytest.mark.parametrize("inference", [False, True]) +def test_harness_converts_selected_host_partitions(monkeypatch, inference): + request = _request() + if inference: + request.update(operation="predict", fit_input_selection=["X", "y"]) + request["dataset"]["shape"]["train_rows"] = 32 + case = resolve_case(request, PROFILE) + X = np.arange(case.generated_rows * 8).reshape(-1, 8) + y = np.arange(case.generated_rows) + calls = [] + + class RecordingProvider(Provider): + def convert_data(self, value, *, estimator, role, representation): + assert estimator == case.estimator + assert representation == "array" + calls.append((role, value)) + return value + 1 + + provider = get_provider("scikit-learn") + preparation_calls = [] + client = object() + + def prepare_inputs(inputs, runtime): + assert runtime is client + preparation_calls.append(inputs) + return tuple(value + 10 for value in inputs) + + monkeypatch.setattr(provider.backend, "prepare_inputs", prepare_inputs) + monkeypatch.setitem( + PROVIDERS, + "scikit-learn", + RecordingProvider(provider.backend, provider.catalog), + ) + monkeypatch.setattr(harness, "generate_data", lambda case: (X, y)) + monkeypatch.setattr( + provider.backend, "load_estimator", lambda spec: object + ) + prepared = harness._prepare_case( + provider.backend, + _suite(case), + case, + provider.estimator_spec("PCA"), + client, + ) + assert prepared.estimator_class is object + assert len(preparation_calls) == 1 + assert len(preparation_calls[0]) == (3 if inference else 1) + for actual, (_, original) in zip(preparation_calls[0], calls, strict=True): + np.testing.assert_array_equal(actual, original + 1) + assert [role for role, _ in calls] == ( + ["X", "X", "y"] if inference else ["X"] + ) + measured_X = X[32:] if inference else X + np.testing.assert_array_equal(calls[0][1], measured_X) + np.testing.assert_array_equal(prepared.operation_args[0], measured_X + 11) + if inference: + np.testing.assert_array_equal(calls[1][1], X[:32]) + np.testing.assert_array_equal(calls[2][1], y[:32]) + np.testing.assert_array_equal(prepared.fit_args[0], X[:32] + 11) + np.testing.assert_array_equal(prepared.fit_args[1], y[:32] + 11) + else: + assert prepared.fit_args is None + + +@pytest.mark.parametrize("shape", [(64, 8), (64,)]) +def test_native_conversion_preserves_shape_and_values(shape): + host = np.ones(shape) + device = get_backend("cuml").convert_data(host, representation="array") + np.testing.assert_array_equal(host, device.get()) + + +@pytest.mark.parametrize("provider", ["scikit-learn", "cuml", "cuml.dask"]) +@pytest.mark.parametrize( + "representation", ["array", "csr", "dataframe", "series"] +) +def test_structural_conversion_contract(provider, representation): + backend = get_provider(provider).backend + value = np.arange(12, dtype=np.float32) + if representation in {"csr", "dataframe"}: + value = value.reshape(4, 3) + if provider == "cuml.dask" and representation == "csr": + with pytest.raises(ValueError, match="CSR"): + backend.convert_data(value, representation=representation) + return + if provider == "cuml.dask": + pytest.importorskip( + "dask.array" if representation == "array" else "dask_cudf" + ) + converted = backend.convert_data(value, representation=representation) + if hasattr(converted, "compute"): + converted = converted.compute() + if hasattr(converted, "to_numpy"): + converted = converted.to_numpy() + elif hasattr(converted, "get"): + converted = converted.get() + if sparse.issparse(converted): + converted = converted.toarray() + np.testing.assert_array_equal(converted, value) + assert converted.dtype == value.dtype + + +@pytest.mark.parametrize("provider", ["scikit-learn", "cuml", "cuml.dask"]) +def test_conversion_rejects_unknown_requirements(provider): + backend = get_provider(provider).backend + with pytest.raises(ValueError, match="representation"): + backend.convert_data(np.zeros(4), representation="unknown")