Skip to content
40 changes: 28 additions & 12 deletions python/cuml/cuml/benchmark/backends/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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}"
)
Comment on lines +122 to +124

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can this ever trigger? representation is an InputRepresentation literal and the only producer is _prepare_case (plus the "series" override in DaskProvider), so no caller should pass anything else. The same branch is repeated in NativeCumlBackend.convert_data and DaskBackend.convert_data, and test_conversion_rejects_unknown_requirements only exercises this probably unreachable path. I'd drop the raises and the test. If you want to keep one, a one-line comment explaining when it can fire would help. I guess it depends on what we assume about harness authors :-/


def prepare_inputs(
self, inputs: tuple[Any, ...], runtime: Any = None
Expand Down
36 changes: 23 additions & 13 deletions python/cuml/cuml/benchmark/backends/cuml.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down
69 changes: 27 additions & 42 deletions python/cuml/cuml/benchmark/backends/dask.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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")
Comment on lines +41 to +42

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DaskBackend.runtime already rejects suites with any CSR case (SuiteError("Dask CSR inputs are not supported yet")) before a case is prepared, so I don't think this can be reached. Could we keep the check in one place?

if representation in {"dataframe", "series"}:
local = NativeCumlBackend.convert_data(
self, value, representation=representation
)
Comment on lines +43 to +46

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you think of having both backends get the host conversion from super() (it resolves to Backend.convert_data for both), then each doing its own device step?

# backends/cuml.py: NativeCumlBackend.convert_data
if representation == "array":
    return importlib.import_module("cupy").asarray(value)
host = super().convert_data(value, representation=representation)
if representation == "csr":
    return importlib.import_module("cupyx.scipy.sparse").csr_matrix(
        host
    )
return importlib.import_module("cudf").from_pandas(host)
# backends/dask.py: DaskBackend.convert_data
if representation == "csr":
    raise ValueError("Dask CSR inputs are not supported yet")
if representation != "array":
    host = super().convert_data(value, representation=representation)
    local = importlib.import_module("cudf").from_pandas(host)
    return importlib.import_module("dask_cudf").from_cudf(
        local, npartitions=2
    )
# ... array path unchanged

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
Expand Down
80 changes: 40 additions & 40 deletions python/cuml/cuml/benchmark/harness.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This makes two sources for the backend in _prepare_case. Conversion goes through suite.provider_spec.backend, while load_estimator and prepare_inputs use the backend argument. In production these are the same object (see _benchmark_case), but nothing enforces it.

The new tests have to patch the provider's backend and swap the entry in PROVIDERS to keep them consistent. Could _prepare_case take the backend from provider.backend (or receive the provider instead of the backend) so there is only one?


# 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:],
)


Expand Down
27 changes: 25 additions & 2 deletions python/cuml/cuml/benchmark/providers/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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:
Expand Down
38 changes: 36 additions & 2 deletions python/cuml/cuml/benchmark/providers/dask.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down Expand Up @@ -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)
Loading
Loading