From e03abfff44a9f126d5af2fe5f36d8ee889274a27 Mon Sep 17 00:00:00 2001 From: Simon Adorf Date: Tue, 10 Nov 2026 13:12:05 -0600 Subject: [PATCH 1/4] Add optional held-out quality scoring to benchmark cases --- docs/source/developer_guide/benchmarking.md | 27 ++ python/cuml/cuml/benchmark/_schema.py | 9 + python/cuml/cuml/benchmark/datasets.py | 33 ++ python/cuml/cuml/benchmark/harness.py | 92 +++- python/cuml/cuml/benchmark/metrics.py | 121 ++++++ python/cuml/cuml/benchmark/scoring.py | 135 ++++++ python/cuml/cuml/benchmark/suite.py | 52 +++ .../cuml/cuml/benchmark/suites/scoring.yaml | 45 ++ python/cuml/tests/test_benchmark.py | 403 +++++++++++++++++- 9 files changed, 885 insertions(+), 32 deletions(-) create mode 100644 python/cuml/cuml/benchmark/metrics.py create mode 100644 python/cuml/cuml/benchmark/scoring.py create mode 100644 python/cuml/cuml/benchmark/suites/scoring.yaml diff --git a/docs/source/developer_guide/benchmarking.md b/docs/source/developer_guide/benchmarking.md index ee301f35d0..0e6c58a674 100644 --- a/docs/source/developer_guide/benchmarking.md +++ b/docs/source/developer_guide/benchmarking.md @@ -216,6 +216,33 @@ Each provider saves its results file after every case, including failures. The results JSON Schema is packaged at `cuml/benchmark/schemas/benchmark-result.schema.json`. +## Optional quality scoring + +Add a registered scorer to a case; omit `scoring` to collect timings only: + +```yaml +scoring: + name: r2 + evaluation_rows: 1024 + parameters: {force_finite: false} # Optional scorer arguments. +``` + +Fitting cases require `evaluation_rows` for held-out evaluation, profile-scaled +with a minimum of 32 rows. Training and evaluation data are generated together, +so adding or resizing evaluation data can change training inputs and workload IDs. +For `predict` cases, omit `evaluation_rows`: scoring uses the measured predictions +and existing held-out population. + +Scoring runs after each measurement, outside timing and dispatch verification; +warmups are not scored. Metrics are saved in each observation's `metrics` list. +Exceptions or nonfinite scores fail the case while preserving its timing; low +valid scores do not. Resume requires matching scoring settings. Compare scores +only when both workload IDs and scoring descriptors match. + +See `scoring.py` for registered scorers, `metrics.py` for metric implementations, +and `suites/scoring.yaml` for examples. The built-in `estimators` manifest opts +supported cases into scoring and leaves the others unscored. + ## Resume a run ```bash diff --git a/python/cuml/cuml/benchmark/_schema.py b/python/cuml/cuml/benchmark/_schema.py index 939a855d20..abc6b58432 100644 --- a/python/cuml/cuml/benchmark/_schema.py +++ b/python/cuml/cuml/benchmark/_schema.py @@ -46,6 +46,14 @@ class DatasetManifest(msgspec.Struct, forbid_unknown_fields=True): format: Literal["dense", "csr"] = "dense" +class ScoringManifest(msgspec.Struct, forbid_unknown_fields=True): + """Select a registered quality scorer and optional held-out fitting size.""" + + name: NonEmptyString + parameters: dict[str, Any] = msgspec.field(default_factory=dict) + evaluation_rows: PositiveCount | None = None + + class CaseManifest(msgspec.Struct, forbid_unknown_fields=True): """Specify an estimator operation and its dataset inputs.""" @@ -57,6 +65,7 @@ class CaseManifest(msgspec.Struct, forbid_unknown_fields=True): # Omission inherits the suite providers; a list narrows applicability. providers: Providers | None = None tags: list[str] = msgspec.field(default_factory=list) + scoring: ScoringManifest | None = None # Required for inference, forbidden for fitting (validated by the loader). fit_input_selection: InputSelection | None = None # Omission inherits the profile timeout; explicit null disables it. diff --git a/python/cuml/cuml/benchmark/datasets.py b/python/cuml/cuml/benchmark/datasets.py index f959cff783..09d99ed385 100644 --- a/python/cuml/cuml/benchmark/datasets.py +++ b/python/cuml/cuml/benchmark/datasets.py @@ -7,6 +7,7 @@ import importlib import math +from dataclasses import dataclass from typing import TYPE_CHECKING, Any if TYPE_CHECKING: @@ -163,6 +164,38 @@ def resolve_dataset( return parameters +@dataclass(frozen=True) +class HostPartitions: + """Keep host populations separate from estimator argument selection. + + Measured data aliases training data for fitting operations. For inference, + it contains the disjoint rows consumed by the timed operation. + """ + + training: dict[str, Any] + measured: dict[str, Any] + evaluation: dict[str, Any] | None = None + + +def partition_data(case: ResolvedCase, X: Any, y: Any) -> HostPartitions: + """Partition generated host rows by contiguous slicing, without sampling.""" + training = {"X": X, "y": y} + measured = training + if case.lifecycle == "inference": + split = case.training_rows + training = {"X": X[:split], "y": y[:split]} + measured = {"X": X[split:], "y": y[split:]} + evaluation = None + if case.scoring is not None: + if case.lifecycle == "fit": + split = case.training_rows + training = measured = {"X": X[:split], "y": y[:split]} + evaluation = {"X": X[split:], "y": y[split:]} + else: + evaluation = measured + return HostPartitions(training, measured, evaluation) + + def generate_data(case: ResolvedCase) -> tuple[Any, Any]: """Generate inputs from dataset settings, independently of the estimator. diff --git a/python/cuml/cuml/benchmark/harness.py b/python/cuml/cuml/benchmark/harness.py index 4d056813b8..8c29ebb568 100644 --- a/python/cuml/cuml/benchmark/harness.py +++ b/python/cuml/cuml/benchmark/harness.py @@ -22,8 +22,9 @@ from ._subprocess import SubprocessExited, SubprocessTimeout, run_in_subprocess from ._utils import _failure, _gpu_components, _jsonable, _now, atomic_write from .backends.base import Backend -from .datasets import generate_data +from .datasets import generate_data, partition_data from .providers.base import EstimatorSpec +from .scoring import SCORERS, evaluate from .suite import ResolvedCase, Suite, SuiteError, Workload logger = logging.getLogger("cuml.benchmark") @@ -78,6 +79,11 @@ def _run_record(suite: Suite, argv: list[str]) -> dict[str, Any]: "warmups": c.warmups, "repetitions": c.repetitions, "timeout_sec": c.timeout_sec, + **( + {"scoring": c.scoring.descriptor()} + if c.scoring + else {} + ), } for c in suite.cases ], @@ -110,6 +116,11 @@ def _base_result( "timeout_sec": case.timeout_sec, "resolved_dataset_parameters": dict(case.dataset_parameters), "tags": list(case.tags), + **( + {"scoring": case.scoring.descriptor()} + if case.scoring + else {} + ), } }, } @@ -124,6 +135,8 @@ class _PreparedCase: estimator_class: type[Any] operation_args: tuple[Any, ...] fit_args: tuple[Any, ...] | None + evaluation_X: Any = None + evaluation_y: Any = None def _prepare_case( @@ -138,14 +151,8 @@ def _prepare_case( provider = suite.provider_spec # Generate and partition host data. - X, y = generate_data(case) + partitions = partition_data(case, *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 = ( @@ -167,16 +174,36 @@ def convert(inputs, selection): for name in selection ) - operation_args = convert(measured, case.input_selection) - fit_args = () if is_fit else convert(train, case.fit_input_selection) + operation_args = convert(partitions.measured, case.input_selection) + fit_args = ( + () + if is_fit + else convert(partitions.training, case.fit_input_selection) + ) + + evaluation_args = () + if is_fit and case.scoring is not None: + scorer = SCORERS[case.scoring.name] + evaluation_args = convert( + partitions.evaluation, scorer.input_selection + ) - # Materialize both groups together, then restore their boundary. - prepared = backend.prepare_inputs(operation_args + fit_args, client) - boundary = len(operation_args) + # Materialize all inputs together, then restore their group boundaries. + prepared = backend.prepare_inputs( + operation_args + fit_args + evaluation_args, client + ) + operation_end = len(operation_args) + fit_end = operation_end + len(fit_args) + evaluation_X = evaluation_y = None + if case.scoring is not None: + evaluation_X = prepared[fit_end] if is_fit else prepared[0] + evaluation_y = partitions.evaluation["y"] return _PreparedCase( estimator_class=estimator_class, - operation_args=prepared[:boundary], - fit_args=None if is_fit else prepared[boundary:], + operation_args=prepared[:operation_end], + fit_args=None if is_fit else prepared[operation_end:fit_end], + evaluation_X=evaluation_X, + evaluation_y=evaluation_y, ) @@ -209,15 +236,17 @@ def _run_observation( role: str, repetition: int, sequence: int, -) -> dict[str, Any]: - """Measure one synchronized operation and record verification results.""" +) -> tuple[dict[str, Any], Any]: + """Measure an operation and return its observation and output for scoring.""" with backend.instrumentation(suite, role, repetition) as verification: backend.synchronize() start = time.perf_counter() output = getattr(estimator, case.operation)(*prepared.operation_args) - backend.synchronize(output) + # Fitting can return the estimator itself, not a lazy output. Probing + # distributed estimators for a Dask graph triggers remote lookups. + backend.synchronize(None if output is estimator else output) elapsed = time.perf_counter() - start - return { + observation = { "id": f"{role}-{repetition}", "sequence": sequence, "role": role, @@ -228,6 +257,7 @@ def _run_observation( "metrics": [], "extensions": dict(verification.extensions), } + return observation, output def _record_case_failure( @@ -294,7 +324,7 @@ def set_phase(value: str) -> None: backend, prepared, case, client, result ) set_phase("warmup" if role == "warmup" else "timed_execution") - observation = _run_observation( + observation, output = _run_observation( backend, suite, case, @@ -318,6 +348,28 @@ def set_phase(value: str) -> None: if observation["outcome"]["status"] == "failed": result["outcome"] = copy.deepcopy(observation["outcome"]) return result + if role == "measurement" and case.scoring is not None: + set_phase("scoring") + try: + observation["metrics"] = evaluate( + case.scoring, + estimator=estimator, + output=output, + X=prepared.evaluation_X, + y=prepared.evaluation_y, + operation=case.operation, + ) + backend.synchronize() + except Exception as exc: + error = _failure(exc, "scoring") + observation["outcome"] = error + observation["extensions"].setdefault(EXTENSION, {})[ + "traceback" + ] = traceback.format_exc() + result["outcome"] = copy.deepcopy(error) + return result + # Do not retain outputs across repetitions (especially on GPU). + del output result["outcome"] = {"status": "success"} return result except Exception as exc: diff --git a/python/cuml/cuml/benchmark/metrics.py b/python/cuml/cuml/benchmark/metrics.py new file mode 100644 index 0000000000..47127461f9 --- /dev/null +++ b/python/cuml/cuml/benchmark/metrics.py @@ -0,0 +1,121 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Host metrics for held-out benchmark scoring.""" + +from __future__ import annotations + +import numpy as np + + +def metric(name, value, *, higher=False, unit="dimensionless"): + """Build one scalar artifact metric.""" + return [ + { + "name": name, + "value": float(value), + "unit": unit, + "direction": "higher_is_better" if higher else "lower_is_better", + } + ] + + +def dense(value): + """Collect a bounded scoring output as a host array.""" + from .scoring import _to_host + + value = _to_host(value) + if hasattr(value, "toarray"): + value = value.toarray() + return np.asarray(value) + + +def relative_error(actual, expected): + """Return relative Frobenius error, with an absolute zero-reference fallback.""" + actual, expected = ( + dense(actual).astype(np.float64), + dense(expected).astype(np.float64), + ) + if actual.shape != expected.shape: + raise ValueError( + f"scoring shape mismatch: {actual.shape} != {expected.shape}" + ) + return np.linalg.norm(actual - expected) / max( + np.linalg.norm(expected), np.finfo(float).eps + ) + + +def reconstruction(*, estimator, X, parameters, **unused): + """Measure held-out transform/inverse-transform reconstruction error.""" + if parameters: + raise ValueError("reconstruction has no parameters") + reconstructed = estimator.inverse_transform(estimator.transform(X)) + return metric( + "relative_reconstruction_error", + relative_error(reconstructed, X), + ) + + +def projection(*, estimator, X, parameters, **unused): + """Measure relative distance distortion over deterministic held-out pairs.""" + pairs = parameters.get("pairs", 1024) + if set(parameters) - {"pairs"} or not isinstance(pairs, int) or pairs < 1: + raise ValueError("projection requires a positive pairs count") + Z = dense(estimator.transform(X)).astype(np.float64) + X = dense(X).astype(np.float64) + rng = np.random.default_rng(42) + left = rng.integers(len(X), size=pairs) + right = (left + rng.integers(1, len(X), size=pairs)) % len(X) + original = np.linalg.norm(X[left] - X[right], axis=1) + projected = np.linalg.norm(Z[left] - Z[right], axis=1) + nonzero = original > 0 + if not np.any(nonzero): + raise ValueError("projection evaluation requires distinct points") + return metric( + "mean_relative_distance_distortion", + np.mean(np.abs(projected[nonzero] / original[nonzero] - 1)), + ) + + +def trustworthiness(*, estimator, X, parameters, **unused): + """Evaluate a bounded held-out embedding without comparing coordinates.""" + from sklearn.manifold import trustworthiness as score + + Z = dense(estimator.transform(X)) + return metric( + "trustworthiness", + score(dense(X), Z, **parameters), + higher=True, + ) + + +def covariance(*, estimator, X, parameters, **unused): + """Compute common Gaussian log likelihood from fitted mean and covariance.""" + if parameters: + raise ValueError("gaussian_log_likelihood has no parameters") + covariance = dense(estimator.covariance_).astype(np.float64) + centered = dense(X).astype(np.float64) - dense(estimator.location_) + sign, logdet = np.linalg.slogdet(covariance) + if sign <= 0: + raise ValueError("fitted covariance is not positive definite") + quadratic = np.sum( + centered * np.linalg.solve(covariance, centered.T).T, axis=1 + ) + value = -0.5 * np.mean( + centered.shape[1] * np.log(2 * np.pi) + logdet + quadratic + ) + return metric( + "mean_gaussian_log_likelihood", value, higher=True, unit="nats/sample" + ) + + +def density(*, estimator, X, parameters, **unused): + """Evaluate held-out log density with the fitted provider estimator.""" + if parameters: + raise ValueError("log_density has no parameters") + return metric( + "mean_log_density", + dense(estimator.score_samples(X)).mean(), + higher=True, + unit="nats/sample", + ) diff --git a/python/cuml/cuml/benchmark/scoring.py b/python/cuml/cuml/benchmark/scoring.py new file mode 100644 index 0000000000..c2c7297218 --- /dev/null +++ b/python/cuml/cuml/benchmark/scoring.py @@ -0,0 +1,135 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Named, provider-independent quality scorers, executed outside timing.""" + +from __future__ import annotations + +import importlib +import math +from dataclasses import dataclass +from typing import Any, Callable + +from . import metrics + + +@dataclass(frozen=True) +class Scorer: + """Versioned scorer returning artifact metric dictionaries. + + Increment ``version`` whenever evaluation semantics change. Callbacks must + not refit or mutate the estimator, which inference repetitions may reuse. + """ + + version: str + evaluate: Callable[..., list[dict[str, Any]]] + dataset: str | tuple[str, ...] + operations: tuple[str, ...] = ( + "fit", + "fit_predict", + "fit_transform", + "predict", + ) + input_selection: tuple[str, ...] = ("X",) + + +def _to_host(value: Any) -> Any: + """Collect distributed outputs, then transfer device arrays to the host.""" + if hasattr(value, "compute"): + value = value.compute() + if hasattr(value, "to_numpy"): + value = value.to_numpy() + if hasattr(value, "get"): + value = value.get() + return value + + +def _prediction_metric( + *, estimator, output, X, y, operation, parameters, name, **unused +) -> list[dict[str, Any]]: + """Evaluate a measured prediction or predict on held-out fitting inputs.""" + prediction = output if operation == "predict" else estimator.predict(X) + metric = getattr(importlib.import_module("sklearn.metrics"), name) + value = float(metric(y, _to_host(prediction), **parameters)) + return [ + { + "name": name, + "value": value, + "unit": "dimensionless", + "direction": "higher_is_better", + } + ] + + +def _accuracy(**kwargs): + return _prediction_metric(name="accuracy_score", **kwargs) + + +def _r2(*, parameters, **kwargs): + return _prediction_metric( + name="r2_score", + parameters={"force_finite": False, **parameters}, + **kwargs, + ) + + +def _adjusted_rand(**kwargs): + return _prediction_metric(name="adjusted_rand_score", **kwargs) + + +SCORERS = { + "accuracy": Scorer( + "1", _accuracy, ("classification", "positive", "matrix", "categorical") + ), + "r2": Scorer("2", _r2, "regression"), + "adjusted_rand": Scorer("1", _adjusted_rand, "blobs"), + "reconstruction": Scorer("1", metrics.reconstruction, "blobs"), + "distance_distortion": Scorer("1", metrics.projection, "blobs"), + "trustworthiness": Scorer("1", metrics.trustworthiness, "blobs"), + "gaussian_log_likelihood": Scorer("1", metrics.covariance, "blobs"), + "log_density": Scorer("1", metrics.density, "blobs"), +} + + +@dataclass(frozen=True) +class ScoringSpec: + """Resolved case scoring configuration, separate from timing identity.""" + + name: str + parameters: dict[str, Any] + evaluation_rows: int + + def descriptor(self) -> dict[str, Any]: + """Describe the evaluation contract for resume and score comparison.""" + return { + "name": self.name, + "version": SCORERS[self.name].version, + "parameters": dict(self.parameters), + "evaluation_rows": self.evaluation_rows, + "population": "held-out", + "partition": "disjoint-contiguous-v1", + } + + +def evaluate( + spec: ScoringSpec, + *, + estimator: Any, + output: Any, + X: Any, + y: Any, + operation: str, +) -> list[dict[str, Any]]: + """Run an internal scorer and reject nonfinite metric values.""" + metrics = SCORERS[spec.name].evaluate( + estimator=estimator, + output=output, + X=X, + y=y, + operation=operation, + parameters=dict(spec.parameters), + ) + for metric in metrics: + if not math.isfinite(metric["value"]): + raise ValueError("scorer returned a nonfinite metric") + return metrics diff --git a/python/cuml/cuml/benchmark/suite.py b/python/cuml/cuml/benchmark/suite.py index c7eb45a29b..2551822262 100644 --- a/python/cuml/cuml/benchmark/suite.py +++ b/python/cuml/cuml/benchmark/suite.py @@ -24,6 +24,7 @@ resolve_dtypes, ) from .providers import PROVIDERS, Provider, get_provider +from .scoring import SCORERS, ScoringSpec if TYPE_CHECKING: from ._schema import CaseManifest, ProfileManifest @@ -163,6 +164,7 @@ class ResolvedCase: repetitions: int timeout_sec: float | None tags: tuple[str, ...] = () + scoring: ScoringSpec | None = None @property def lifecycle(self) -> Literal["fit", "inference"]: @@ -187,6 +189,12 @@ def workload(self) -> Workload: partition="disjoint-contiguous-v1", fit_input_selection=list(self.fit_input_selection), ) + elif self.scoring is not None: + dataset_parameters.update( + train_rows=self.training_rows, + evaluation_rows=self.scoring.evaluation_rows, + partition="disjoint-contiguous-v1", + ) return Workload( algorithm=self.estimator, dataset={ @@ -280,6 +288,49 @@ def _resolve_case( training_rows = max(1, round(shape.train_rows * profile.size_scale)) measured_rows = rows generated_rows = training_rows + measured_rows + scoring = None + if request.scoring is not None: + requested = request.scoring + if requested.name not in SCORERS: + raise SuiteError(f"unknown scorer {requested.name!r}") + scorer = SCORERS[requested.name] + datasets = ( + (scorer.dataset,) + if isinstance(scorer.dataset, str) + else scorer.dataset + ) + if dataset.generator not in datasets: + raise SuiteError( + f"scorer {requested.name!r} requires {scorer.dataset!r} data" + ) + if not is_fit and request.input_selection != list( + scorer.input_selection + ): + raise SuiteError( + "prediction scoring requires input_selection: [X]" + ) + if request.operation not in scorer.operations: + raise SuiteError( + f"scorer {requested.name!r} does not support {request.operation!r}" + ) + if is_fit: + if requested.evaluation_rows is None: + raise SuiteError("scored fitting requires evaluation_rows") + evaluation_rows = max( + 32, round(requested.evaluation_rows * profile.size_scale) + ) + generated_rows += evaluation_rows + else: + if requested.evaluation_rows is not None: + raise SuiteError( + "inference scoring uses measured rows; omit evaluation_rows" + ) + evaluation_rows = measured_rows + scoring = ScoringSpec( + requested.name, + copy.deepcopy(requested.parameters), + evaluation_rows, + ) dtype = dataset.dtype if isinstance(dtype, schema.DtypeMapping): dtype = {"X": dtype.X, "y": dtype.y} @@ -296,6 +347,7 @@ def _resolve_case( return ResolvedCase( estimator=request.estimator, tags=tuple(request.tags), + scoring=scoring, dataset=dataset.generator, operation=request.operation, generated_rows=generated_rows, diff --git a/python/cuml/cuml/benchmark/suites/scoring.yaml b/python/cuml/cuml/benchmark/suites/scoring.yaml new file mode 100644 index 0000000000..89a01f9119 --- /dev/null +++ b/python/cuml/cuml/benchmark/suites/scoring.yaml @@ -0,0 +1,45 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Run with --suite path/to/scoring.yaml; this is an opt-in example suite. +version: 2 +name: held-out-scoring +providers: [cuml, scikit-learn, cuml.accel] +profiles: + standard: + warmups: 1 + repetitions: 3 + size_scale: 1.0 + smoke: + warmups: 1 + repetitions: 2 + size_scale: 0.1 +cases: + - estimator: LogisticRegression + dataset: + generator: classification + shape: {rows: 4096, features: 16} + dtype: float32 + operation: fit + input_selection: [X, y] + parameters: {max_iter: 200} + scoring: {name: accuracy, evaluation_rows: 1024} + - estimator: LinearRegression + dataset: + generator: regression + shape: {rows: 4096, features: 16} + dtype: float32 + operation: fit + input_selection: [X, y] + parameters: {} + scoring: {name: r2, evaluation_rows: 1024} + - estimator: KMeans + dataset: + generator: blobs + shape: {rows: 4096, features: 16} + dtype: float32 + parameters: {centers: 5} + operation: fit_predict + input_selection: [X] + parameters: {n_clusters: 5, random_state: 42} + scoring: {name: adjusted_rand, evaluation_rows: 1024} diff --git a/python/cuml/tests/test_benchmark.py b/python/cuml/tests/test_benchmark.py index 5b1f36ff4f..d5d3b2287e 100644 --- a/python/cuml/tests/test_benchmark.py +++ b/python/cuml/tests/test_benchmark.py @@ -31,7 +31,7 @@ from cuml import benchmark from cuml.benchmark import _runner as coordinator from cuml.benchmark import _subprocess as runner -from cuml.benchmark import cli, harness +from cuml.benchmark import cli, harness, scoring from cuml.benchmark._hashing import canonical_json from cuml.benchmark._selection import compile_expression, select_plan from cuml.benchmark.backends import base as base_backend @@ -39,7 +39,7 @@ from cuml.benchmark.backends import get_backend from cuml.benchmark.backends.accel import ACCEL_EXTENSION from cuml.benchmark.backends.base import Backend, GPUBackend -from cuml.benchmark.datasets import generate_data +from cuml.benchmark.datasets import generate_data, partition_data from cuml.benchmark.providers import PROVIDERS, Provider, get_provider from cuml.benchmark.providers.base import EstimatorSpec from cuml.benchmark.schemas import benchmark_result_schema @@ -1001,7 +1001,10 @@ def predict(self, *args): @pytest.mark.parametrize("operation", ["fit", "predict"]) -def test_only_synchronized_operation_is_timed(monkeypatch, operation): +@pytest.mark.parametrize("fit_returns_self", [False, True]) +def test_only_synchronized_operation_is_timed( + monkeypatch, operation, fit_returns_self +): events = [] class Output: @@ -1022,7 +1025,7 @@ def __init__(self, **kwargs): def fit(self, *args): events.append("fit") - return output + return self if fit_returns_self else output def predict(self, *args): events.append("predict") @@ -1040,13 +1043,12 @@ def generate(case): backend = get_backend("cpu") monkeypatch.setattr(backend, "load_estimator", lambda spec: Estimator) monkeypatch.setattr(harness, "generate_data", generate) - monkeypatch.setattr( - backend, - "synchronize", - lambda value=None: events.append( - "sync-output" if value is output else "sync" - ), - ) + + def synchronize(value=None): + assert not isinstance(value, Estimator) + events.append("sync-output" if value is output else "sync") + + monkeypatch.setattr(backend, "synchronize", synchronize) ticks = iter([10, 10.25, 20, 20.25, 30, 30.25]) monkeypatch.setattr( harness.time, @@ -1059,7 +1061,10 @@ def generate(case): request["dataset"]["shape"]["train_rows"] = 32 result = _benchmark(resolve_case(request, PROFILE)) assert result["outcome"] == {"status": "success"} - observation = ["sync", "clock", operation, "sync-output", "clock"] + output_sync = ( + "sync" if operation == "fit" and fit_returns_self else "sync-output" + ) + observation = ["sync", "clock", operation, output_sync, "clock"] assert events == ( ["generate", "construct", "fit", "sync"] + observation * 3 if operation == "predict" @@ -3196,6 +3201,51 @@ def prepare_inputs(inputs, runtime): assert prepared.fit_args is None +@pytest.mark.parametrize("kind", ["dense", "csr", "categorical"]) +@pytest.mark.parametrize("mode", ["training", "inference"]) +def test_host_partitions(kind, mode): + request = _request() + if mode == "inference": + request.update(operation="transform", fit_input_selection=["X"]) + request["dataset"]["shape"]["train_rows"] = 128 + if kind == "csr": + request["dataset"]["format"] = "csr" + elif kind == "categorical": + request["dataset"]["generator"] = "categorical" + case = resolve_case(request, PROFILE) + X, y = generate_data(case) + partitions = partition_data(case, X, y) + assert partitions.training["X"].shape[0] == case.training_rows + assert partitions.measured["X"].shape[0] == case.measured_rows + assert (partitions.measured is partitions.training) == ( + mode != "inference" + ) + if mode == "training": + assert partitions.training["X"] is X + assert partitions.training["y"] is y + + def assert_partition(actual, rows): + expected_X = X[rows] + assert type(actual["X"]) is type(X) + if kind == "categorical": + pd.testing.assert_frame_equal(actual["X"], expected_X) + else: + np.testing.assert_array_equal( + actual["X"].toarray() if kind == "csr" else actual["X"], + expected_X.toarray() if kind == "csr" else expected_X, + ) + np.testing.assert_array_equal(actual["y"], y[rows]) + assert np.shares_memory(actual["y"], y) + + assert_partition(partitions.training, slice(None, case.training_rows)) + assert_partition( + partitions.measured, + slice(case.training_rows, None) + if mode == "inference" + else slice(None, case.training_rows), + ) + + @pytest.mark.parametrize("shape", [(64, 8), (64,)]) def test_native_conversion_preserves_shape_and_values(shape): host = np.ones(shape) @@ -3238,3 +3288,332 @@ 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") + + +def _scored_request(name="r2", operation="fit"): + estimator, dataset, parameters = { + "r2": ("LinearRegression", "regression", {}), + "accuracy": ( + "LogisticRegression", + "classification", + {"max_iter": 200}, + ), + "adjusted_rand": ( + "KMeans", + "blobs", + {"n_clusters": 5, "random_state": 42}, + ), + }[name] + request = _request( + estimator=estimator, + dataset={"generator": dataset, "shape": {"rows": 128, "features": 8}}, + parameters=parameters, + operation=operation, + input_selection=["X"] if name == "adjusted_rand" else ["X", "y"], + scoring={"name": name, "evaluation_rows": 64}, + ) + if operation == "predict": + request["fit_input_selection"] = request["input_selection"] + request["input_selection"] = ["X"] + request["dataset"]["shape"]["train_rows"] = 128 + request["scoring"].pop("evaluation_rows") + return request + + +@pytest.mark.parametrize("name", ["accuracy", "r2", "adjusted_rand"]) +@pytest.mark.parametrize("operation", ["fit", "predict"]) +@pytest.mark.parametrize("provider", ["scikit-learn", "cuml"]) +def test_scoring_metrics_match_held_out_reference(name, operation, provider): + case = resolve_case(_scored_request(name, operation), PROFILE) + result = _benchmark(case, provider=provider) + assert result["outcome"] == {"status": "success"}, result + assert result["observations"][0]["metrics"] == [] + partitions = partition_data(case, *generate_data(case)) + spec = get_provider("scikit-learn").estimator_spec(case.estimator) + estimator = Backend().load_estimator(spec)(**case.parameters) + inputs = [ + partitions.training[role] + for role in (case.fit_input_selection or case.input_selection) + ] + estimator.fit(*inputs) + expected = scoring.evaluate( + case.scoring, + estimator=estimator, + output=None, + X=partitions.evaluation["X"], + y=partitions.evaluation["y"], + operation="fit", + )[0]["value"] + for observation in result["observations"][1:]: + (metric,) = observation["metrics"] + assert metric["value"] == pytest.approx(expected, abs=0.05) + assert observation["timings"][0]["value"] >= 0 + assert ( + case.workload_id() + == resolve_case( + _scored_request(name, operation), PROFILE + ).workload_id() + ) + + +def test_scoring_split_and_identity(): + request = _scored_request() + case = resolve_case(request, PROFILE) + X, y = generate_data(case) + partitions = partition_data(case, X, y) + assert case.generated_rows == 192 + assert partitions.training is partitions.measured + np.testing.assert_array_equal(partitions.training["X"], X[:128]) + np.testing.assert_array_equal(partitions.evaluation["X"], X[128:]) + np.testing.assert_array_equal(partitions.evaluation["y"], y[128:]) + assert not np.shares_memory( + partitions.training["X"], partitions.evaluation["X"] + ) + unscored = resolve_case({**request, "scoring": None}, PROFILE) + assert case.workload_id() != unscored.workload_id() + changed = copy.deepcopy(request) + changed["scoring"]["evaluation_rows"] += 1 + assert case.workload_id() != resolve_case(changed, PROFILE).workload_id() + changed = copy.deepcopy(request) + changed["scoring"]["parameters"] = {"force_finite": False} + assert case.workload_id() == resolve_case(changed, PROFILE).workload_id() + scaled = resolve_case(request, {**PROFILE, "size_scale": 0.5}) + assert scaled.scoring.evaluation_rows == 32 + assert scaled.training_rows == 64 + + +@pytest.mark.parametrize( + "change,match", + [ + ({"name": "missing", "evaluation_rows": 64}, "unknown scorer"), + ( + {"name": "accuracy", "evaluation_rows": 64}, + "requires.*classification", + ), + ({"name": "r2"}, "requires evaluation_rows"), + ({"name": "r2", "evaluation_rows": 0}, "invalid"), + ], +) +def test_invalid_scoring_configuration(change, match): + with pytest.raises(SuiteError, match=match): + resolve_case({**_scored_request(), "scoring": change}, PROFILE) + + +@pytest.mark.parametrize("failure", [False, True]) +def test_scoring_outside_timing_and_verification(monkeypatch, failure): + case = resolve_case(_scored_request(), PROFILE) + backend = get_provider("scikit-learn").backend + events = [] + + @contextlib.contextmanager + def instrumentation(*args): + events.append("enter") + yield base_backend.VerificationResult() + events.append("exit") + + def clock(): + events.append("clock") + return len(events) + + original = scoring.SCORERS["r2"] + + def score(**kwargs): + assert events[-3:] == ["clock", "clock", "exit"] + events.append("score") + if failure: + raise RuntimeError("evaluation failed") + return original.evaluate(**kwargs) + + monkeypatch.setattr(backend, "instrumentation", instrumentation) + monkeypatch.setattr(harness.time, "perf_counter", clock) + monkeypatch.setitem( + scoring.SCORERS, "r2", replace(original, evaluate=score) + ) + result = _benchmark(case) + assert events.count("score") == (1 if failure else 2) + if failure: + assert result["outcome"]["last_phase"] == "scoring" + assert len(result["observations"]) == 2 + observation = result["observations"][-1] + assert observation["outcome"]["status"] == "failed" + assert observation["timings"][0]["value"] == 1 + else: + assert result["outcome"]["status"] == "success" + + +@pytest.mark.parametrize("force_finite", [None, True, False]) +def test_r2_constant_targets(force_finite): + case = resolve_case(_scored_request(), PROFILE) + parameters = {} if force_finite is None else {"force_finite": force_finite} + spec = replace(case.scoring, parameters=parameters) + kwargs = dict( + estimator=None, + output=np.zeros(32), + X=None, + y=np.ones(32), + operation="predict", + ) + with np.errstate(divide="ignore", invalid="ignore"): + if force_finite is True: + assert scoring.evaluate(spec, **kwargs)[0]["value"] == 0 + else: + with pytest.raises(ValueError, match="nonfinite"): + scoring.evaluate(spec, **kwargs) + + +@pytest.mark.parametrize("value", [float("nan"), float("inf"), -float("inf")]) +def test_nonfinite_scoring_results_fail_case(monkeypatch, value): + original = scoring.SCORERS["r2"] + + def score(**kwargs): + metrics = original.evaluate(**kwargs) + metrics[0]["value"] = value + return metrics + + monkeypatch.setitem( + scoring.SCORERS, "r2", replace(original, evaluate=score) + ) + result = _benchmark(resolve_case(_scored_request(), PROFILE)) + assert result["outcome"]["last_phase"] == "scoring" + assert result["observations"][-1]["timings"] + assert result["observations"][-1]["metrics"] == [] + + +@pytest.mark.parametrize("change", ["version", "parameters", "disabled"]) +def test_scoring_artifact_and_resume(tmp_path, monkeypatch, change): + case = resolve_case(_scored_request(), PROFILE) + suite = _suite(case) + path = tmp_path / "scoring.json" + artifact = harness.run_suite(suite, path) + _validate_artifact(artifact) + assert ( + artifact["results"][0]["extensions"][harness.EXTENSION]["scoring"] + == case.scoring.descriptor() + ) + assert ( + harness.run_suite(suite, path, resume=True)["results"] + == artifact["results"] + ) + if change == "version": + original = scoring.SCORERS["r2"] + monkeypatch.setitem( + scoring.SCORERS, + "r2", + replace(original, version=original.version + "-changed"), + ) + elif change == "parameters": + suite = _suite( + replace( + case, + scoring=replace( + case.scoring, parameters={"force_finite": False} + ), + ) + ) + else: + suite = _suite(replace(case, scoring=None)) + with pytest.raises(SuiteError, match="matching suite"): + harness.run_suite(suite, path, resume=True) + + +def test_scoring_failure_artifact_preserves_timing(tmp_path): + request = _scored_request() + request["scoring"]["parameters"] = {"unknown_parameter": True} + artifact = harness.run_suite( + _suite(resolve_case(request, PROFILE)), tmp_path / "failed.json" + ) + _validate_artifact(artifact) + (result,) = artifact["results"] + assert result["outcome"]["last_phase"] == "scoring" + assert len(result["observations"]) == 2 + observation = result["observations"][-1] + assert observation["outcome"]["last_phase"] == "scoring" + assert observation["timings"] + assert observation["metrics"] == [] + + +def test_scoring_inference_reuses_measured_predictions(monkeypatch): + case = resolve_case(_scored_request(operation="predict"), PROFILE) + from sklearn.linear_model import LinearRegression + + original = LinearRegression.predict + calls = [] + + def predict(self, X): + calls.append(X) + return original(self, X) + + monkeypatch.setattr(LinearRegression, "predict", predict) + result = _benchmark(case) + assert result["outcome"] == {"status": "success"} + assert len(calls) == case.warmups + case.repetitions + + +@pytest.mark.parametrize( + "estimator,scorer,parameters,dataset", + [ + ("PCA", "reconstruction", {"n_components": 2}, "blobs"), + ("TruncatedSVD", "reconstruction", {"n_components": 2}, "blobs"), + ( + "GaussianRandomProjection", + "distance_distortion", + {"n_components": 2, "random_state": 42}, + "blobs", + ), + ("EmpiricalCovariance", "gaussian_log_likelihood", {}, "blobs"), + ("LedoitWolf", "gaussian_log_likelihood", {}, "blobs"), + ], +) +@pytest.mark.parametrize("provider", ["cuml", "scikit-learn"]) +def test_scorer_provider_integration( + estimator, scorer, parameters, dataset, provider +): + case = resolve_case( + _request( + estimator=estimator, + operation="fit", + input_selection=["X"], + dataset={ + "generator": dataset, + "shape": {"rows": 512, "features": 8}, + }, + parameters=parameters, + scoring={"name": scorer, "evaluation_rows": 64}, + ), + PROFILE, + ) + result = _benchmark(case, provider=provider) + assert result["outcome"] == {"status": "success"}, result + (metric,) = result["observations"][-1]["metrics"] + assert np.isfinite(metric["value"]) + + +@pytest.mark.parametrize("provider", ["scikit-learn", "cuml", "cuml.dask"]) +def test_covariance_metric_matches_analytic_density(provider): + from cuml.benchmark.metrics import covariance + + estimator = SimpleNamespace(covariance_=np.eye(2), location_=np.zeros(2)) + expected = -np.log(2 * np.pi) - 0.5 + actual = covariance( + estimator=estimator, + X=get_provider(provider).backend.convert_data( + np.array([[1.0, 0.0], [0.0, 1.0]]), representation="array" + ), + parameters={}, + ) + assert actual[0]["value"] == pytest.approx(expected) + + +@pytest.mark.parametrize("provider", ["scikit-learn", "cuml", "cuml.dask"]) +def test_projection_metric_preserves_distances(provider): + from cuml.benchmark.metrics import projection + + X = np.random.default_rng(42).normal(size=(32, 4)) + actual = projection( + estimator=SimpleNamespace(transform=lambda X: X), + X=get_provider(provider).backend.convert_data( + X, representation="array" + ), + parameters={"pairs": 100}, + ) + assert actual[0]["value"] == pytest.approx(0) From 4602753d35bee6ac348a018d5f42cd02eea89971 Mon Sep 17 00:00:00 2001 From: Simon Adorf Date: Tue, 10 Nov 2026 13:12:05 -0600 Subject: [PATCH 2/4] Enable quality scoring for supported estimator benchmarks --- .../cuml/benchmark/suites/estimators.yaml | 159 ++++++++++++++++++ 1 file changed, 159 insertions(+) diff --git a/python/cuml/cuml/benchmark/suites/estimators.yaml b/python/cuml/cuml/benchmark/suites/estimators.yaml index 1fe8b3cd20..89c6c1f037 100644 --- a/python/cuml/cuml/benchmark/suites/estimators.yaml +++ b/python/cuml/cuml/benchmark/suites/estimators.yaml @@ -38,6 +38,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: LogisticRegression tags: [balanced] @@ -58,6 +59,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: LogisticRegression tags: [wide] @@ -78,6 +80,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: LinearRegression tags: [thin] @@ -90,6 +93,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: r2, evaluation_rows: 4096} - estimator: LinearRegression tags: [balanced] @@ -102,6 +106,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: r2, evaluation_rows: 4096} - estimator: LinearRegression tags: [wide] @@ -114,6 +119,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: r2, evaluation_rows: 4096} - estimator: Ridge tags: [thin] @@ -126,6 +132,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: r2, evaluation_rows: 4096} - estimator: Ridge tags: [balanced] @@ -138,6 +145,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: r2, evaluation_rows: 4096} - estimator: Ridge tags: [wide] @@ -150,6 +158,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: r2, evaluation_rows: 4096} - estimator: ElasticNet tags: [thin] @@ -164,6 +173,7 @@ cases: parameters: alpha: 0.1 l1_ratio: 0.5 + scoring: {name: r2, evaluation_rows: 4096} - estimator: ElasticNet tags: [balanced] @@ -178,6 +188,7 @@ cases: parameters: alpha: 0.1 l1_ratio: 0.5 + scoring: {name: r2, evaluation_rows: 4096} - estimator: ElasticNet tags: [wide] @@ -192,6 +203,7 @@ cases: parameters: alpha: 0.1 l1_ratio: 0.5 + scoring: {name: r2, evaluation_rows: 4096} - estimator: Lasso tags: [thin] @@ -204,6 +216,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: r2, evaluation_rows: 4096} - estimator: Lasso tags: [balanced] @@ -216,6 +229,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: r2, evaluation_rows: 4096} - estimator: Lasso tags: [wide] @@ -228,6 +242,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: r2, evaluation_rows: 4096} - estimator: KernelRidge tags: [thin] @@ -240,6 +255,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: r2, evaluation_rows: 512} - estimator: KernelRidge tags: [balanced] @@ -252,6 +268,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: r2, evaluation_rows: 512} - estimator: KernelRidge tags: [wide] @@ -264,6 +281,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: r2, evaluation_rows: 512} - estimator: MBSGDRegressor tags: [thin] @@ -276,6 +294,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: r2, evaluation_rows: 4096} - estimator: MBSGDRegressor tags: [balanced] @@ -288,6 +307,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: r2, evaluation_rows: 4096} - estimator: MBSGDRegressor tags: [wide] @@ -300,6 +320,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: r2, evaluation_rows: 4096} - estimator: KMeans tags: [thin] @@ -318,6 +339,7 @@ cases: n_clusters: 8 max_iter: 300 n_init: 1 + scoring: {name: adjusted_rand, evaluation_rows: 4096} - estimator: KMeans tags: [balanced] @@ -336,6 +358,7 @@ cases: n_clusters: 8 max_iter: 300 n_init: 1 + scoring: {name: adjusted_rand, evaluation_rows: 4096} - estimator: KMeans tags: [wide] @@ -354,6 +377,7 @@ cases: n_clusters: 8 max_iter: 300 n_init: 1 + scoring: {name: adjusted_rand, evaluation_rows: 4096} - estimator: AgglomerativeClustering tags: [thin] @@ -371,6 +395,7 @@ cases: n_clusters: 8 metric: euclidean linkage: single + # Unscored: no common held-out evaluation in this configuration. - estimator: AgglomerativeClustering tags: [balanced] @@ -388,6 +413,7 @@ cases: n_clusters: 8 metric: euclidean linkage: single + # Unscored: no common held-out evaluation in this configuration. - estimator: AgglomerativeClustering tags: [wide] @@ -405,6 +431,7 @@ cases: n_clusters: 8 metric: euclidean linkage: single + # Unscored: no common held-out evaluation in this configuration. - estimator: SpectralClustering tags: [thin] @@ -424,6 +451,7 @@ cases: n_neighbors: 10 n_init: 1 random_state: 42 + # Unscored: no common held-out evaluation in this configuration. - estimator: SpectralClustering tags: [balanced] @@ -443,6 +471,7 @@ cases: n_neighbors: 10 n_init: 1 random_state: 42 + # Unscored: no common held-out evaluation in this configuration. - estimator: SpectralClustering tags: [wide] @@ -462,6 +491,7 @@ cases: n_neighbors: 10 n_init: 1 random_state: 42 + # Unscored: no common held-out evaluation in this configuration. - estimator: NearestNeighbors tags: [thin] @@ -479,6 +509,7 @@ cases: fit_input_selection: [X] parameters: n_neighbors: 64 + # Unscored: reference-based scoring is not supported. - estimator: NearestNeighbors tags: [thin] @@ -498,6 +529,7 @@ cases: n_neighbors: 64 algorithm: brute n_jobs: -1 + # Unscored: reference-based scoring is not supported. - estimator: NearestNeighbors tags: [balanced] @@ -515,6 +547,7 @@ cases: fit_input_selection: [X] parameters: n_neighbors: 64 + # Unscored: reference-based scoring is not supported. - estimator: NearestNeighbors tags: [balanced] @@ -534,6 +567,7 @@ cases: n_neighbors: 64 algorithm: brute n_jobs: -1 + # Unscored: reference-based scoring is not supported. - estimator: NearestNeighbors tags: [wide] @@ -551,6 +585,7 @@ cases: fit_input_selection: [X] parameters: n_neighbors: 64 + # Unscored: reference-based scoring is not supported. - estimator: NearestNeighbors tags: [wide] @@ -570,6 +605,7 @@ cases: n_neighbors: 64 algorithm: brute n_jobs: -1 + # Unscored: reference-based scoring is not supported. - estimator: PCA tags: [thin] @@ -585,6 +621,7 @@ cases: input_selection: [X] parameters: n_components: 10 + scoring: {name: reconstruction, evaluation_rows: 4096} - estimator: PCA tags: [thin] @@ -600,6 +637,7 @@ cases: input_selection: [X] parameters: n_components: 25 + scoring: {name: reconstruction, evaluation_rows: 4096} - estimator: PCA tags: [balanced] @@ -615,6 +653,7 @@ cases: input_selection: [X] parameters: n_components: 10 + scoring: {name: reconstruction, evaluation_rows: 4096} - estimator: PCA tags: [balanced] @@ -630,6 +669,7 @@ cases: input_selection: [X] parameters: n_components: 25 + scoring: {name: reconstruction, evaluation_rows: 4096} - estimator: PCA tags: [wide] @@ -645,6 +685,7 @@ cases: input_selection: [X] parameters: n_components: 10 + scoring: {name: reconstruction, evaluation_rows: 4096} - estimator: PCA tags: [wide] @@ -660,6 +701,7 @@ cases: input_selection: [X] parameters: n_components: 25 + scoring: {name: reconstruction, evaluation_rows: 4096} - estimator: IncrementalPCA tags: [thin] @@ -675,6 +717,7 @@ cases: input_selection: [X] parameters: n_components: 10 + scoring: {name: reconstruction, evaluation_rows: 4096} - estimator: IncrementalPCA tags: [balanced] @@ -690,6 +733,7 @@ cases: input_selection: [X] parameters: n_components: 10 + scoring: {name: reconstruction, evaluation_rows: 4096} - estimator: IncrementalPCA tags: [wide] @@ -705,6 +749,7 @@ cases: input_selection: [X] parameters: n_components: 10 + scoring: {name: reconstruction, evaluation_rows: 4096} - estimator: TruncatedSVD tags: [thin] @@ -720,6 +765,7 @@ cases: input_selection: [X] parameters: n_components: 10 + scoring: {name: reconstruction, evaluation_rows: 4096} - estimator: TruncatedSVD tags: [balanced] @@ -735,6 +781,7 @@ cases: input_selection: [X] parameters: n_components: 10 + scoring: {name: reconstruction, evaluation_rows: 4096} - estimator: TruncatedSVD tags: [wide] @@ -750,6 +797,7 @@ cases: input_selection: [X] parameters: n_components: 10 + scoring: {name: reconstruction, evaluation_rows: 4096} - estimator: GaussianRandomProjection tags: [thin] @@ -765,6 +813,7 @@ cases: input_selection: [X] parameters: n_components: 10 + scoring: {name: distance_distortion, evaluation_rows: 4096, parameters: {pairs: 1024}} - estimator: GaussianRandomProjection tags: [thin] @@ -780,6 +829,7 @@ cases: input_selection: [X] parameters: n_components: 25 + scoring: {name: distance_distortion, evaluation_rows: 4096, parameters: {pairs: 1024}} - estimator: GaussianRandomProjection tags: [balanced] @@ -795,6 +845,7 @@ cases: input_selection: [X] parameters: n_components: 10 + scoring: {name: distance_distortion, evaluation_rows: 4096, parameters: {pairs: 1024}} - estimator: GaussianRandomProjection tags: [balanced] @@ -810,6 +861,7 @@ cases: input_selection: [X] parameters: n_components: 25 + scoring: {name: distance_distortion, evaluation_rows: 4096, parameters: {pairs: 1024}} - estimator: GaussianRandomProjection tags: [wide] @@ -825,6 +877,7 @@ cases: input_selection: [X] parameters: n_components: 10 + scoring: {name: distance_distortion, evaluation_rows: 4096, parameters: {pairs: 1024}} - estimator: GaussianRandomProjection tags: [wide] @@ -840,6 +893,7 @@ cases: input_selection: [X] parameters: n_components: 25 + scoring: {name: distance_distortion, evaluation_rows: 4096, parameters: {pairs: 1024}} - estimator: SparseRandomProjection tags: [thin] @@ -855,6 +909,7 @@ cases: input_selection: [X] parameters: n_components: 10 + scoring: {name: distance_distortion, evaluation_rows: 4096, parameters: {pairs: 1024}} - estimator: SparseRandomProjection tags: [thin] @@ -870,6 +925,7 @@ cases: input_selection: [X] parameters: n_components: 25 + scoring: {name: distance_distortion, evaluation_rows: 4096, parameters: {pairs: 1024}} - estimator: SparseRandomProjection tags: [balanced] @@ -885,6 +941,7 @@ cases: input_selection: [X] parameters: n_components: 10 + scoring: {name: distance_distortion, evaluation_rows: 4096, parameters: {pairs: 1024}} - estimator: SparseRandomProjection tags: [balanced] @@ -900,6 +957,7 @@ cases: input_selection: [X] parameters: n_components: 25 + scoring: {name: distance_distortion, evaluation_rows: 4096, parameters: {pairs: 1024}} - estimator: SparseRandomProjection tags: [wide] @@ -915,6 +973,7 @@ cases: input_selection: [X] parameters: n_components: 10 + scoring: {name: distance_distortion, evaluation_rows: 4096, parameters: {pairs: 1024}} - estimator: SparseRandomProjection tags: [wide] @@ -930,6 +989,7 @@ cases: input_selection: [X] parameters: n_components: 25 + scoring: {name: distance_distortion, evaluation_rows: 4096, parameters: {pairs: 1024}} - estimator: EmpiricalCovariance tags: [thin] @@ -944,6 +1004,7 @@ cases: operation: fit input_selection: [X] parameters: {} + scoring: {name: gaussian_log_likelihood, evaluation_rows: 4096} - estimator: EmpiricalCovariance tags: [balanced] @@ -958,6 +1019,7 @@ cases: operation: fit input_selection: [X] parameters: {} + scoring: {name: gaussian_log_likelihood, evaluation_rows: 4096} - estimator: EmpiricalCovariance tags: [wide] @@ -972,6 +1034,7 @@ cases: operation: fit input_selection: [X] parameters: {} + scoring: {name: gaussian_log_likelihood, evaluation_rows: 4096} - estimator: LedoitWolf tags: [thin] @@ -986,6 +1049,7 @@ cases: operation: fit input_selection: [X] parameters: {} + scoring: {name: gaussian_log_likelihood, evaluation_rows: 4096} - estimator: LedoitWolf tags: [balanced] @@ -1000,6 +1064,7 @@ cases: operation: fit input_selection: [X] parameters: {} + scoring: {name: gaussian_log_likelihood, evaluation_rows: 4096} - estimator: LedoitWolf tags: [wide] @@ -1014,6 +1079,7 @@ cases: operation: fit input_selection: [X] parameters: {} + scoring: {name: gaussian_log_likelihood, evaluation_rows: 4096} - estimator: RandomForestClassifier tags: [thin] @@ -1035,6 +1101,7 @@ cases: input_selection: [X, y] parameters: n_estimators: 20 + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: RandomForestClassifier tags: [thin] @@ -1057,6 +1124,7 @@ cases: parameters: n_estimators: 20 n_jobs: -1 + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: RandomForestClassifier tags: [balanced] @@ -1078,6 +1146,7 @@ cases: input_selection: [X, y] parameters: n_estimators: 20 + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: RandomForestClassifier tags: [balanced] @@ -1100,6 +1169,7 @@ cases: parameters: n_estimators: 20 n_jobs: -1 + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: RandomForestClassifier tags: [wide] @@ -1121,6 +1191,7 @@ cases: input_selection: [X, y] parameters: n_estimators: 20 + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: RandomForestClassifier tags: [wide] @@ -1143,6 +1214,7 @@ cases: parameters: n_estimators: 20 n_jobs: -1 + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: RandomForestRegressor tags: [thin] @@ -1156,6 +1228,7 @@ cases: input_selection: [X, y] parameters: n_estimators: 20 + scoring: {name: r2, evaluation_rows: 4096} - estimator: RandomForestRegressor tags: [thin] @@ -1170,6 +1243,7 @@ cases: parameters: n_estimators: 20 n_jobs: -1 + scoring: {name: r2, evaluation_rows: 4096} - estimator: RandomForestRegressor tags: [balanced] @@ -1183,6 +1257,7 @@ cases: input_selection: [X, y] parameters: n_estimators: 20 + scoring: {name: r2, evaluation_rows: 4096} - estimator: RandomForestRegressor tags: [balanced] @@ -1197,6 +1272,7 @@ cases: parameters: n_estimators: 20 n_jobs: -1 + scoring: {name: r2, evaluation_rows: 4096} - estimator: RandomForestRegressor tags: [wide] @@ -1210,6 +1286,7 @@ cases: input_selection: [X, y] parameters: n_estimators: 20 + scoring: {name: r2, evaluation_rows: 4096} - estimator: RandomForestRegressor tags: [wide] @@ -1224,6 +1301,7 @@ cases: parameters: n_estimators: 20 n_jobs: -1 + scoring: {name: r2, evaluation_rows: 4096} - estimator: SVC tags: [thin] @@ -1245,6 +1323,7 @@ cases: input_selection: [X, y] parameters: kernel: rbf + scoring: {name: accuracy, evaluation_rows: 512} - estimator: SVC tags: [balanced] @@ -1266,6 +1345,7 @@ cases: input_selection: [X, y] parameters: kernel: rbf + scoring: {name: accuracy, evaluation_rows: 512} - estimator: SVC tags: [wide] @@ -1287,6 +1367,7 @@ cases: input_selection: [X, y] parameters: kernel: rbf + scoring: {name: accuracy, evaluation_rows: 512} - estimator: SVR tags: [thin] @@ -1300,6 +1381,7 @@ cases: input_selection: [X, y] parameters: kernel: rbf + scoring: {name: r2, evaluation_rows: 512} - estimator: SVR tags: [balanced] @@ -1313,6 +1395,7 @@ cases: input_selection: [X, y] parameters: kernel: rbf + scoring: {name: r2, evaluation_rows: 512} - estimator: SVR tags: [wide] @@ -1326,6 +1409,7 @@ cases: input_selection: [X, y] parameters: kernel: rbf + scoring: {name: r2, evaluation_rows: 512} - estimator: LinearSVC tags: [thin] @@ -1346,6 +1430,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: LinearSVC tags: [balanced] @@ -1366,6 +1451,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: LinearSVC tags: [wide] @@ -1386,6 +1472,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: LinearSVR tags: [thin] @@ -1398,6 +1485,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: r2, evaluation_rows: 4096} - estimator: LinearSVR tags: [balanced] @@ -1410,6 +1498,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: r2, evaluation_rows: 4096} - estimator: LinearSVR tags: [wide] @@ -1422,6 +1511,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: r2, evaluation_rows: 4096} - estimator: DBSCAN tags: [thin] @@ -1438,6 +1528,7 @@ cases: parameters: eps: 3 min_samples: 2 + # Unscored: no common held-out evaluation in this configuration. - estimator: DBSCAN tags: [thin] @@ -1455,6 +1546,7 @@ cases: eps: 3 min_samples: 2 algorithm: brute + # Unscored: no common held-out evaluation in this configuration. - estimator: DBSCAN tags: [balanced] @@ -1471,6 +1563,7 @@ cases: parameters: eps: 3 min_samples: 2 + # Unscored: no common held-out evaluation in this configuration. - estimator: DBSCAN tags: [balanced] @@ -1488,6 +1581,7 @@ cases: eps: 3 min_samples: 2 algorithm: brute + # Unscored: no common held-out evaluation in this configuration. - estimator: DBSCAN tags: [wide] @@ -1504,6 +1598,7 @@ cases: parameters: eps: 3 min_samples: 2 + # Unscored: no common held-out evaluation in this configuration. - estimator: DBSCAN tags: [wide] @@ -1521,6 +1616,7 @@ cases: eps: 3 min_samples: 2 algorithm: brute + # Unscored: no common held-out evaluation in this configuration. - estimator: KNeighborsClassifier tags: [thin] @@ -1543,6 +1639,7 @@ cases: input_selection: [X] fit_input_selection: [X, y] parameters: {} + scoring: {name: accuracy} - estimator: KNeighborsClassifier tags: [balanced] @@ -1565,6 +1662,7 @@ cases: input_selection: [X] fit_input_selection: [X, y] parameters: {} + scoring: {name: accuracy} - estimator: KNeighborsClassifier tags: [wide] @@ -1587,6 +1685,7 @@ cases: input_selection: [X] fit_input_selection: [X, y] parameters: {} + scoring: {name: accuracy} - estimator: KNeighborsRegressor tags: [thin] @@ -1601,6 +1700,7 @@ cases: input_selection: [X] fit_input_selection: [X, y] parameters: {} + scoring: {name: r2} - estimator: KNeighborsRegressor tags: [balanced] @@ -1615,6 +1715,7 @@ cases: input_selection: [X] fit_input_selection: [X, y] parameters: {} + scoring: {name: r2} - estimator: KNeighborsRegressor tags: [wide] @@ -1629,6 +1730,7 @@ cases: input_selection: [X] fit_input_selection: [X, y] parameters: {} + scoring: {name: r2} - estimator: StandardScaler tags: [thin] @@ -1649,6 +1751,7 @@ cases: operation: fit_transform input_selection: [X] parameters: {} + # Unscored: reference-based scoring is not supported. - estimator: StandardScaler tags: [balanced] @@ -1669,6 +1772,7 @@ cases: operation: fit_transform input_selection: [X] parameters: {} + # Unscored: reference-based scoring is not supported. - estimator: StandardScaler tags: [wide] @@ -1689,6 +1793,7 @@ cases: operation: fit_transform input_selection: [X] parameters: {} + # Unscored: reference-based scoring is not supported. - estimator: MinMaxScaler tags: [thin] @@ -1709,6 +1814,7 @@ cases: operation: fit_transform input_selection: [X] parameters: {} + # Unscored: reference-based scoring is not supported. - estimator: MinMaxScaler tags: [balanced] @@ -1729,6 +1835,7 @@ cases: operation: fit_transform input_selection: [X] parameters: {} + # Unscored: reference-based scoring is not supported. - estimator: MinMaxScaler tags: [wide] @@ -1749,6 +1856,7 @@ cases: operation: fit_transform input_selection: [X] parameters: {} + # Unscored: reference-based scoring is not supported. - estimator: MaxAbsScaler tags: [thin] @@ -1769,6 +1877,7 @@ cases: operation: fit_transform input_selection: [X] parameters: {} + # Unscored: reference-based scoring is not supported. - estimator: MaxAbsScaler tags: [balanced] @@ -1789,6 +1898,7 @@ cases: operation: fit_transform input_selection: [X] parameters: {} + # Unscored: reference-based scoring is not supported. - estimator: MaxAbsScaler tags: [wide] @@ -1809,6 +1919,7 @@ cases: operation: fit_transform input_selection: [X] parameters: {} + # Unscored: reference-based scoring is not supported. - estimator: Normalizer tags: [thin] @@ -1829,6 +1940,7 @@ cases: operation: fit_transform input_selection: [X] parameters: {} + # Unscored: reference-based scoring is not supported. - estimator: Normalizer tags: [balanced] @@ -1849,6 +1961,7 @@ cases: operation: fit_transform input_selection: [X] parameters: {} + # Unscored: reference-based scoring is not supported. - estimator: Normalizer tags: [wide] @@ -1869,6 +1982,7 @@ cases: operation: fit_transform input_selection: [X] parameters: {} + # Unscored: reference-based scoring is not supported. - estimator: RobustScaler tags: [thin] @@ -1889,6 +2003,7 @@ cases: operation: fit_transform input_selection: [X] parameters: {} + # Unscored: reference-based scoring is not supported. - estimator: RobustScaler tags: [balanced] @@ -1909,6 +2024,7 @@ cases: operation: fit_transform input_selection: [X] parameters: {} + # Unscored: reference-based scoring is not supported. - estimator: RobustScaler tags: [wide] @@ -1929,6 +2045,7 @@ cases: operation: fit_transform input_selection: [X] parameters: {} + # Unscored: reference-based scoring is not supported. - estimator: PolynomialFeatures tags: [thin] @@ -1950,6 +2067,7 @@ cases: input_selection: [X] parameters: degree: 2 + # Unscored: reference-based scoring is not supported. - estimator: PolynomialFeatures tags: [balanced] @@ -1971,6 +2089,7 @@ cases: input_selection: [X] parameters: degree: 2 + # Unscored: reference-based scoring is not supported. - estimator: PolynomialFeatures tags: [wide] @@ -1992,6 +2111,7 @@ cases: input_selection: [X] parameters: degree: 2 + # Unscored: reference-based scoring is not supported. - estimator: Binarizer tags: [thin] @@ -2012,6 +2132,7 @@ cases: operation: fit_transform input_selection: [X] parameters: {} + # Unscored: reference-based scoring is not supported. - estimator: Binarizer tags: [balanced] @@ -2032,6 +2153,7 @@ cases: operation: fit_transform input_selection: [X] parameters: {} + # Unscored: reference-based scoring is not supported. - estimator: Binarizer tags: [wide] @@ -2052,6 +2174,7 @@ cases: operation: fit_transform input_selection: [X] parameters: {} + # Unscored: reference-based scoring is not supported. - estimator: KBinsDiscretizer tags: [thin] @@ -2075,6 +2198,7 @@ cases: n_bins: 16 encode: ordinal strategy: uniform + # Unscored: reference-based scoring is not supported. - estimator: KBinsDiscretizer tags: [balanced] @@ -2098,6 +2222,7 @@ cases: n_bins: 16 encode: ordinal strategy: uniform + # Unscored: reference-based scoring is not supported. - estimator: KBinsDiscretizer tags: [wide] @@ -2121,6 +2246,7 @@ cases: n_bins: 16 encode: ordinal strategy: uniform + # Unscored: reference-based scoring is not supported. - estimator: PowerTransformer tags: [thin] @@ -2142,6 +2268,7 @@ cases: input_selection: [X] parameters: method: yeo-johnson + # Unscored: reference-based scoring is not supported. - estimator: PowerTransformer tags: [balanced] @@ -2163,6 +2290,7 @@ cases: input_selection: [X] parameters: method: yeo-johnson + # Unscored: reference-based scoring is not supported. - estimator: PowerTransformer tags: [wide] @@ -2184,6 +2312,7 @@ cases: input_selection: [X] parameters: method: yeo-johnson + # Unscored: reference-based scoring is not supported. - estimator: QuantileTransformer tags: [thin] @@ -2207,6 +2336,7 @@ cases: n_quantiles: 1000 subsample: 100000 random_state: 42 + # Unscored: reference-based scoring is not supported. - estimator: QuantileTransformer tags: [balanced] @@ -2230,6 +2360,7 @@ cases: n_quantiles: 1000 subsample: 100000 random_state: 42 + # Unscored: reference-based scoring is not supported. - estimator: QuantileTransformer tags: [wide] @@ -2253,6 +2384,7 @@ cases: n_quantiles: 1000 subsample: 100000 random_state: 42 + # Unscored: reference-based scoring is not supported. - estimator: LabelEncoder providers: [cuml, scikit-learn, cuml.accel, cuml.dask] @@ -2272,6 +2404,7 @@ cases: operation: fit_transform input_selection: [y] parameters: {} + # Unscored: reference-based scoring is not supported. - estimator: LabelEncoder providers: [cuml, scikit-learn, cuml.accel, cuml.dask] @@ -2291,6 +2424,7 @@ cases: operation: fit_transform input_selection: [y] parameters: {} + # Unscored: reference-based scoring is not supported. - estimator: LabelEncoder providers: [cuml, scikit-learn, cuml.accel, cuml.dask] @@ -2310,6 +2444,7 @@ cases: operation: fit_transform input_selection: [y] parameters: {} + # Unscored: reference-based scoring is not supported. - estimator: LabelBinarizer providers: [cuml, scikit-learn, cuml.accel, cuml.dask] @@ -2329,6 +2464,7 @@ cases: operation: fit_transform input_selection: [y] parameters: {} + # Unscored: reference-based scoring is not supported. - estimator: LabelBinarizer providers: [cuml, scikit-learn, cuml.accel, cuml.dask] @@ -2348,6 +2484,7 @@ cases: operation: fit_transform input_selection: [y] parameters: {} + # Unscored: reference-based scoring is not supported. - estimator: LabelBinarizer providers: [cuml, scikit-learn, cuml.accel, cuml.dask] @@ -2367,6 +2504,7 @@ cases: operation: fit_transform input_selection: [y] parameters: {} + # Unscored: reference-based scoring is not supported. - estimator: TSNE tags: [thin] @@ -2381,6 +2519,7 @@ cases: operation: fit input_selection: [X] parameters: {} + # Unscored: no common held-out evaluation in this configuration. - estimator: TSNE tags: [balanced] @@ -2395,6 +2534,7 @@ cases: operation: fit input_selection: [X] parameters: {} + # Unscored: no common held-out evaluation in this configuration. - estimator: TSNE tags: [wide] @@ -2409,6 +2549,7 @@ cases: operation: fit input_selection: [X] parameters: {} + # Unscored: no common held-out evaluation in this configuration. - estimator: MultinomialNB tags: [thin] @@ -2421,6 +2562,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: MultinomialNB tags: [balanced] @@ -2433,6 +2575,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: MultinomialNB tags: [wide] @@ -2445,6 +2588,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: GaussianNB tags: [thin] @@ -2465,6 +2609,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: GaussianNB tags: [balanced] @@ -2485,6 +2630,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: GaussianNB tags: [wide] @@ -2505,6 +2651,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: KernelDensity providers: [cuml, cuml.accel] @@ -2520,6 +2667,7 @@ cases: parameters: kernel: gaussian bandwidth: 1.0 + scoring: {name: log_density, evaluation_rows: 512} - estimator: LocalOutlierFactor providers: [cuml, scikit-learn] @@ -2533,6 +2681,7 @@ cases: input_selection: [X] parameters: n_neighbors: 20 + # Unscored: no common held-out evaluation in this configuration. - estimator: BernoulliNB providers: [cuml] @@ -2547,6 +2696,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: ComplementNB providers: [cuml] @@ -2561,6 +2711,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: CategoricalNB providers: [cuml] @@ -2577,6 +2728,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: TargetEncoder providers: [cuml] @@ -2595,6 +2747,7 @@ cases: parameters: smooth: 0.0 seed: 42 + # Unscored: reference-based scoring is not supported. - estimator: TargetEncoder providers: [cuml.accel] @@ -2613,6 +2766,7 @@ cases: parameters: smooth: 0.0 random_state: 42 + # Unscored: reference-based scoring is not supported. - estimator: OneHotEncoder providers: [cuml, cuml.accel, cuml.dask] @@ -2631,6 +2785,7 @@ cases: parameters: sparse_output: false handle_unknown: ignore + # Unscored: reference-based scoring is not supported. - estimator: OrdinalEncoder providers: [cuml, cuml.accel, cuml.dask] @@ -2647,6 +2802,7 @@ cases: operation: fit_transform input_selection: [X] parameters: {} + # Unscored: held-out rows may contain unknown categories. - estimator: SpectralEmbedding providers: [cuml, scikit-learn, cuml.accel] @@ -2661,6 +2817,7 @@ cases: n_components: 2 n_neighbors: 10 random_state: 42 + # Unscored: no common held-out evaluation in this configuration. - estimator: UMAP providers: [cuml, umap-learn, cuml.accel] @@ -2675,6 +2832,7 @@ cases: n_neighbors: 10 n_components: 2 random_state: 42 + scoring: {name: trustworthiness, evaluation_rows: 512, parameters: {n_neighbors: 5}} - estimator: HDBSCAN providers: [cuml, scikit-learn, hdbscan, cuml.accel] @@ -2687,3 +2845,4 @@ cases: input_selection: [X] parameters: min_cluster_size: 5 + # Unscored: no common held-out evaluation in this configuration. From 1f50dd658874a65fa942985258d7fcce084240af Mon Sep 17 00:00:00 2001 From: Simon Adorf Date: Thu, 12 Nov 2026 17:03:53 -0600 Subject: [PATCH 3/4] Separate host-only benchmark metrics from estimator evaluation --- docs/source/developer_guide/benchmarking.md | 21 +- python/cuml/cuml/benchmark/datasets.py | 14 +- python/cuml/cuml/benchmark/harness.py | 14 +- python/cuml/cuml/benchmark/metrics.py | 80 +++++-- python/cuml/cuml/benchmark/scoring.py | 176 ++++++++++------ python/cuml/cuml/benchmark/suite.py | 9 - python/cuml/tests/test_benchmark.py | 220 +++++++++++++++++--- 7 files changed, 380 insertions(+), 154 deletions(-) diff --git a/docs/source/developer_guide/benchmarking.md b/docs/source/developer_guide/benchmarking.md index 0e6c58a674..9ea52a4752 100644 --- a/docs/source/developer_guide/benchmarking.md +++ b/docs/source/developer_guide/benchmarking.md @@ -227,21 +227,12 @@ scoring: parameters: {force_finite: false} # Optional scorer arguments. ``` -Fitting cases require `evaluation_rows` for held-out evaluation, profile-scaled -with a minimum of 32 rows. Training and evaluation data are generated together, -so adding or resizing evaluation data can change training inputs and workload IDs. -For `predict` cases, omit `evaluation_rows`: scoring uses the measured predictions -and existing held-out population. - -Scoring runs after each measurement, outside timing and dispatch verification; -warmups are not scored. Metrics are saved in each observation's `metrics` list. -Exceptions or nonfinite scores fail the case while preserving its timing; low -valid scores do not. Resume requires matching scoring settings. Compare scores -only when both workload IDs and scoring descriptors match. - -See `scoring.py` for registered scorers, `metrics.py` for metric implementations, -and `suites/scoring.yaml` for examples. The built-in `estimators` manifest opts -supported cases into scoring and leaves the others unscored. +Fitting cases require held-out `evaluation_rows`, profile-scaled with a minimum +of 32. Changing this size can change training data and workload IDs. For +`predict`, omit it: scoring reuses measured predictions on held-out inputs. + +Scoring runs outside timing and records quality metrics alongside each +measurement. Invalid scores fail the case; low finite scores do not. ## Resume a run diff --git a/python/cuml/cuml/benchmark/datasets.py b/python/cuml/cuml/benchmark/datasets.py index 09d99ed385..ac39d350b0 100644 --- a/python/cuml/cuml/benchmark/datasets.py +++ b/python/cuml/cuml/benchmark/datasets.py @@ -165,11 +165,11 @@ def resolve_dataset( @dataclass(frozen=True) -class HostPartitions: - """Keep host populations separate from estimator argument selection. +class DatasetPartitions: + """Store training, measured, and optional held-out evaluation populations. - Measured data aliases training data for fitting operations. For inference, - it contains the disjoint rows consumed by the timed operation. + Measured data aliases training data for fitting operations and contains + disjoint rows for inference operations. """ training: dict[str, Any] @@ -177,8 +177,8 @@ class HostPartitions: evaluation: dict[str, Any] | None = None -def partition_data(case: ResolvedCase, X: Any, y: Any) -> HostPartitions: - """Partition generated host rows by contiguous slicing, without sampling.""" +def partition_data(case: ResolvedCase, X: Any, y: Any) -> DatasetPartitions: + """Split generated host data into contiguous workload populations.""" training = {"X": X, "y": y} measured = training if case.lifecycle == "inference": @@ -193,7 +193,7 @@ def partition_data(case: ResolvedCase, X: Any, y: Any) -> HostPartitions: evaluation = {"X": X[split:], "y": y[split:]} else: evaluation = measured - return HostPartitions(training, measured, evaluation) + return DatasetPartitions(training, measured, evaluation) def generate_data(case: ResolvedCase) -> tuple[Any, Any]: diff --git a/python/cuml/cuml/benchmark/harness.py b/python/cuml/cuml/benchmark/harness.py index 8c29ebb568..8d22200ab7 100644 --- a/python/cuml/cuml/benchmark/harness.py +++ b/python/cuml/cuml/benchmark/harness.py @@ -24,7 +24,7 @@ from .backends.base import Backend from .datasets import generate_data, partition_data from .providers.base import EstimatorSpec -from .scoring import SCORERS, evaluate +from .scoring import SCORERS, EvaluationContext, evaluate from .suite import ResolvedCase, Suite, SuiteError, Workload logger = logging.getLogger("cuml.benchmark") @@ -353,11 +353,13 @@ def set_phase(value: str) -> None: try: observation["metrics"] = evaluate( case.scoring, - estimator=estimator, - output=output, - X=prepared.evaluation_X, - y=prepared.evaluation_y, - operation=case.operation, + EvaluationContext( + estimator=estimator, + output=output, + X=prepared.evaluation_X, + y=prepared.evaluation_y, + operation=case.operation, + ), ) backend.synchronize() except Exception as exc: diff --git a/python/cuml/cuml/benchmark/metrics.py b/python/cuml/cuml/benchmark/metrics.py index 47127461f9..c12d26d0c1 100644 --- a/python/cuml/cuml/benchmark/metrics.py +++ b/python/cuml/cuml/benchmark/metrics.py @@ -1,7 +1,11 @@ # SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Host metrics for held-out benchmark scoring.""" +"""Quality metrics accepting only host data, never estimators or device values. + +The scoring layer acquires estimator responses and transfers them to the host +before calling these functions. Sparse host inputs are densified as needed. +""" from __future__ import annotations @@ -21,17 +25,14 @@ def metric(name, value, *, higher=False, unit="dimensionless"): def dense(value): - """Collect a bounded scoring output as a host array.""" - from .scoring import _to_host - - value = _to_host(value) + """Materialize a host value as a dense NumPy array.""" if hasattr(value, "toarray"): value = value.toarray() return np.asarray(value) def relative_error(actual, expected): - """Return relative Frobenius error, with an absolute zero-reference fallback.""" + """Compute Frobenius error normalized by the epsilon-bounded reference norm.""" actual, expected = ( dense(actual).astype(np.float64), dense(expected).astype(np.float64), @@ -45,23 +46,59 @@ def relative_error(actual, expected): ) -def reconstruction(*, estimator, X, parameters, **unused): - """Measure held-out transform/inverse-transform reconstruction error.""" +def accuracy(*, y, prediction, parameters): + """Measure held-out classification accuracy.""" + from sklearn.metrics import accuracy_score + + return metric( + "accuracy_score", + accuracy_score(y, prediction, **parameters), + higher=True, + ) + + +def r2(*, y, prediction, parameters): + """Measure held-out R² without masking nonfinite scores by default.""" + from sklearn.metrics import r2_score + + return metric( + "r2_score", + r2_score( + y, + prediction, + **{"force_finite": False, **parameters}, + ), + higher=True, + ) + + +def adjusted_rand(*, y, prediction, parameters): + """Measure held-out clustering agreement with reference labels.""" + from sklearn.metrics import adjusted_rand_score + + return metric( + "adjusted_rand_score", + adjusted_rand_score(y, prediction, **parameters), + higher=True, + ) + + +def reconstruction(*, X, reconstructed, parameters): + """Measure held-out reconstruction error from host inputs and responses.""" if parameters: raise ValueError("reconstruction has no parameters") - reconstructed = estimator.inverse_transform(estimator.transform(X)) return metric( "relative_reconstruction_error", relative_error(reconstructed, X), ) -def projection(*, estimator, X, parameters, **unused): +def projection(*, X, Z, parameters): """Measure relative distance distortion over deterministic held-out pairs.""" pairs = parameters.get("pairs", 1024) if set(parameters) - {"pairs"} or not isinstance(pairs, int) or pairs < 1: raise ValueError("projection requires a positive pairs count") - Z = dense(estimator.transform(X)).astype(np.float64) + Z = dense(Z).astype(np.float64) X = dense(X).astype(np.float64) rng = np.random.default_rng(42) left = rng.integers(len(X), size=pairs) @@ -77,24 +114,23 @@ def projection(*, estimator, X, parameters, **unused): ) -def trustworthiness(*, estimator, X, parameters, **unused): - """Evaluate a bounded held-out embedding without comparing coordinates.""" +def trustworthiness(*, X, Z, parameters): + """Measure neighborhood preservation in a held-out embedding.""" from sklearn.manifold import trustworthiness as score - Z = dense(estimator.transform(X)) return metric( "trustworthiness", - score(dense(X), Z, **parameters), + score(dense(X), dense(Z), **parameters), higher=True, ) -def covariance(*, estimator, X, parameters, **unused): - """Compute common Gaussian log likelihood from fitted mean and covariance.""" +def covariance(*, X, covariance, location, parameters): + """Compute mean held-out Gaussian log likelihood from fitted parameters.""" if parameters: raise ValueError("gaussian_log_likelihood has no parameters") - covariance = dense(estimator.covariance_).astype(np.float64) - centered = dense(X).astype(np.float64) - dense(estimator.location_) + covariance = dense(covariance).astype(np.float64) + centered = dense(X).astype(np.float64) - dense(location) sign, logdet = np.linalg.slogdet(covariance) if sign <= 0: raise ValueError("fitted covariance is not positive definite") @@ -109,13 +145,13 @@ def covariance(*, estimator, X, parameters, **unused): ) -def density(*, estimator, X, parameters, **unused): - """Evaluate held-out log density with the fitted provider estimator.""" +def density(*, log_density, parameters): + """Compute mean held-out log density from host per-sample values.""" if parameters: raise ValueError("log_density has no parameters") return metric( "mean_log_density", - dense(estimator.score_samples(X)).mean(), + dense(log_density).mean(), higher=True, unit="nats/sample", ) diff --git a/python/cuml/cuml/benchmark/scoring.py b/python/cuml/cuml/benchmark/scoring.py index c2c7297218..0b747f2c17 100644 --- a/python/cuml/cuml/benchmark/scoring.py +++ b/python/cuml/cuml/benchmark/scoring.py @@ -5,7 +5,6 @@ from __future__ import annotations -import importlib import math from dataclasses import dataclass from typing import Any, Callable @@ -14,23 +13,24 @@ @dataclass(frozen=True) -class Scorer: - """Versioned scorer returning artifact metric dictionaries. +class EvaluationContext: + """Provide a fitted estimator, held-out data, and the measured output. - Increment ``version`` whenever evaluation semantics change. Callbacks must - not refit or mutate the estimator, which inference repetitions may reuse. + ``X`` retains the provider's representation; ``y`` remains on the host. + Callbacks must preserve the estimator's fitted state. """ - version: str - evaluate: Callable[..., list[dict[str, Any]]] - dataset: str | tuple[str, ...] - operations: tuple[str, ...] = ( - "fit", - "fit_predict", - "fit_transform", - "predict", - ) - input_selection: tuple[str, ...] = ("X",) + estimator: Any + X: Any + y: Any + output: Any + operation: str + + def predictions(self) -> Any: + """Reuse measured predictions or predict on held-out fitting inputs.""" + if self.operation == "predict": + return self.output + return self.estimator.predict(self.X) def _to_host(value: Any) -> Any: @@ -44,56 +44,115 @@ def _to_host(value: Any) -> Any: return value -def _prediction_metric( - *, estimator, output, X, y, operation, parameters, name, **unused -) -> list[dict[str, Any]]: - """Evaluate a measured prediction or predict on held-out fitting inputs.""" - prediction = output if operation == "predict" else estimator.predict(X) - metric = getattr(importlib.import_module("sklearn.metrics"), name) - value = float(metric(y, _to_host(prediction), **parameters)) - return [ - { - "name": name, - "value": value, - "unit": "dimensionless", - "direction": "higher_is_better", - } +@dataclass(frozen=True) +class Scorer: + """Define a versioned metric callback and its supported workloads. + + Callbacks evaluate fitted estimators while preserving their state. + Increment ``version`` when evaluation semantics change. + """ + + version: str + callback: Callable[ + [EvaluationContext, dict[str, Any]], list[dict[str, Any]] ] + operations: tuple[str, ...] = ( + "fit", + "fit_predict", + "fit_transform", + "predict", + ) + input_selection: tuple[str, ...] = ("X",) + + +def _accuracy(context: EvaluationContext, parameters): + """Collect held-out predictions for host accuracy evaluation.""" + return metrics.accuracy( + y=_to_host(context.y), + prediction=_to_host(context.predictions()), + parameters=parameters, + ) + + +def _r2(context: EvaluationContext, parameters): + """Collect held-out predictions for host R² evaluation.""" + return metrics.r2( + y=_to_host(context.y), + prediction=_to_host(context.predictions()), + parameters=parameters, + ) + + +def _adjusted_rand(context: EvaluationContext, parameters): + """Collect held-out predictions for host clustering evaluation.""" + return metrics.adjusted_rand( + y=_to_host(context.y), + prediction=_to_host(context.predictions()), + parameters=parameters, + ) -def _accuracy(**kwargs): - return _prediction_metric(name="accuracy_score", **kwargs) +def _reconstruction(context: EvaluationContext, parameters): + """Reconstruct held-out inputs using the provider, then collect to host.""" + reconstructed = context.estimator.inverse_transform( + context.estimator.transform(context.X) + ) + return metrics.reconstruction( + X=_to_host(context.X), + reconstructed=_to_host(reconstructed), + parameters=parameters, + ) -def _r2(*, parameters, **kwargs): - return _prediction_metric( - name="r2_score", - parameters={"force_finite": False, **parameters}, - **kwargs, +def _projection(context: EvaluationContext, parameters): + """Project held-out inputs using the provider, then collect to host.""" + Z = context.estimator.transform(context.X) + return metrics.projection( + X=_to_host(context.X), Z=_to_host(Z), parameters=parameters ) -def _adjusted_rand(**kwargs): - return _prediction_metric(name="adjusted_rand_score", **kwargs) +def _trustworthiness(context: EvaluationContext, parameters): + """Embed held-out inputs using the provider, then collect to host.""" + Z = context.estimator.transform(context.X) + return metrics.trustworthiness( + X=_to_host(context.X), Z=_to_host(Z), parameters=parameters + ) + + +def _covariance(context: EvaluationContext, parameters): + """Collect held-out inputs and fitted covariance parameters to host.""" + return metrics.covariance( + X=_to_host(context.X), + covariance=_to_host(context.estimator.covariance_), + location=_to_host(context.estimator.location_), + parameters=parameters, + ) + + +def _density(context: EvaluationContext, parameters): + """Evaluate held-out log density using the provider, then collect to host.""" + return metrics.density( + log_density=_to_host(context.estimator.score_samples(context.X)), + parameters=parameters, + ) SCORERS = { - "accuracy": Scorer( - "1", _accuracy, ("classification", "positive", "matrix", "categorical") - ), - "r2": Scorer("2", _r2, "regression"), - "adjusted_rand": Scorer("1", _adjusted_rand, "blobs"), - "reconstruction": Scorer("1", metrics.reconstruction, "blobs"), - "distance_distortion": Scorer("1", metrics.projection, "blobs"), - "trustworthiness": Scorer("1", metrics.trustworthiness, "blobs"), - "gaussian_log_likelihood": Scorer("1", metrics.covariance, "blobs"), - "log_density": Scorer("1", metrics.density, "blobs"), + "accuracy": Scorer("1", _accuracy), + "r2": Scorer("1", _r2), + "adjusted_rand": Scorer("1", _adjusted_rand), + "reconstruction": Scorer("1", _reconstruction), + "distance_distortion": Scorer("1", _projection), + "trustworthiness": Scorer("1", _trustworthiness), + "gaussian_log_likelihood": Scorer("1", _covariance), + "log_density": Scorer("1", _density), } @dataclass(frozen=True) class ScoringSpec: - """Resolved case scoring configuration, separate from timing identity.""" + """Store a case's scorer, parameters, and evaluation population size.""" name: str parameters: dict[str, Any] @@ -113,22 +172,11 @@ def descriptor(self) -> dict[str, Any]: def evaluate( spec: ScoringSpec, - *, - estimator: Any, - output: Any, - X: Any, - y: Any, - operation: str, + context: EvaluationContext, ) -> list[dict[str, Any]]: - """Run an internal scorer and reject nonfinite metric values.""" - metrics = SCORERS[spec.name].evaluate( - estimator=estimator, - output=output, - X=X, - y=y, - operation=operation, - parameters=dict(spec.parameters), - ) + """Evaluate a registered scorer and validate that metric values are finite.""" + scorer = SCORERS[spec.name] + metrics = scorer.callback(context, dict(spec.parameters)) for metric in metrics: if not math.isfinite(metric["value"]): raise ValueError("scorer returned a nonfinite metric") diff --git a/python/cuml/cuml/benchmark/suite.py b/python/cuml/cuml/benchmark/suite.py index 2551822262..1f68d88d12 100644 --- a/python/cuml/cuml/benchmark/suite.py +++ b/python/cuml/cuml/benchmark/suite.py @@ -294,15 +294,6 @@ def _resolve_case( if requested.name not in SCORERS: raise SuiteError(f"unknown scorer {requested.name!r}") scorer = SCORERS[requested.name] - datasets = ( - (scorer.dataset,) - if isinstance(scorer.dataset, str) - else scorer.dataset - ) - if dataset.generator not in datasets: - raise SuiteError( - f"scorer {requested.name!r} requires {scorer.dataset!r} data" - ) if not is_fit and request.input_selection != list( scorer.input_selection ): diff --git a/python/cuml/tests/test_benchmark.py b/python/cuml/tests/test_benchmark.py index d5d3b2287e..24cf70e655 100644 --- a/python/cuml/tests/test_benchmark.py +++ b/python/cuml/tests/test_benchmark.py @@ -43,6 +43,7 @@ from cuml.benchmark.providers import PROVIDERS, Provider, get_provider from cuml.benchmark.providers.base import EstimatorSpec from cuml.benchmark.schemas import benchmark_result_schema +from cuml.benchmark.scoring import EvaluationContext from cuml.benchmark.suite import ( BUILTIN_SUITES, Suite, @@ -3290,6 +3291,75 @@ def test_conversion_rejects_unknown_requirements(provider): backend.convert_data(np.zeros(4), representation="unknown") +@pytest.mark.parametrize( + "operation", ["fit", "fit_predict", "fit_transform", "predict"] +) +def test_evaluation_context_predictions(operation): + X = np.ones((4, 2)) + held_out_predictions = np.ones(4) + measured_output = np.zeros(4) + calls = [] + + def predict(inputs): + assert inputs is X + calls.append(inputs) + return held_out_predictions + + context = EvaluationContext( + estimator=SimpleNamespace(predict=predict), + X=X, + y=None, + output=measured_output, + operation=operation, + ) + if operation == "predict": + assert context.predictions() is measured_output + assert not calls + else: + assert context.predictions() is held_out_predictions + assert len(calls) == 1 + + +def test_scoring_callback_receives_context_and_parameter_copy(monkeypatch): + context = EvaluationContext(None, None, None, None, "fit") + spec = scoring.ScoringSpec("r2", {"force_finite": False}, 32) + expected = [{"name": "test", "value": 0.5}] + + def callback(actual_context, parameters): + assert actual_context is context + assert parameters == spec.parameters + assert parameters is not spec.parameters + parameters["force_finite"] = True + return expected + + monkeypatch.setitem( + scoring.SCORERS, + "r2", + replace(scoring.SCORERS["r2"], callback=callback), + ) + assert scoring.evaluate(spec, context) is expected + assert spec.parameters == {"force_finite": False} + + +def test_scoring_to_host_collects_before_transfer(): + expected = np.arange(4) + events = [] + + def step(name, output): + def convert(): + events.append(name) + return output + + return convert + + device = SimpleNamespace(get=step("get", expected)) + frame = SimpleNamespace(to_numpy=step("to_numpy", device)) + distributed = SimpleNamespace(compute=step("compute", frame)) + assert scoring._to_host(distributed) is expected + assert events == ["compute", "to_numpy", "get"] + assert scoring._to_host(expected) is expected + + def _scored_request(name="r2", operation="fit"): estimator, dataset, parameters = { "r2": ("LinearRegression", "regression", {}), @@ -3338,11 +3408,13 @@ def test_scoring_metrics_match_held_out_reference(name, operation, provider): estimator.fit(*inputs) expected = scoring.evaluate( case.scoring, - estimator=estimator, - output=None, - X=partitions.evaluation["X"], - y=partitions.evaluation["y"], - operation="fit", + EvaluationContext( + estimator=estimator, + output=None, + X=partitions.evaluation["X"], + y=partitions.evaluation["y"], + operation="fit", + ), )[0]["value"] for observation in result["observations"][1:]: (metric,) = observation["metrics"] @@ -3386,10 +3458,6 @@ def test_scoring_split_and_identity(): "change,match", [ ({"name": "missing", "evaluation_rows": 64}, "unknown scorer"), - ( - {"name": "accuracy", "evaluation_rows": 64}, - "requires.*classification", - ), ({"name": "r2"}, "requires evaluation_rows"), ({"name": "r2", "evaluation_rows": 0}, "invalid"), ], @@ -3417,17 +3485,17 @@ def clock(): original = scoring.SCORERS["r2"] - def score(**kwargs): + def score(context, parameters): assert events[-3:] == ["clock", "clock", "exit"] events.append("score") if failure: raise RuntimeError("evaluation failed") - return original.evaluate(**kwargs) + return original.callback(context, parameters) monkeypatch.setattr(backend, "instrumentation", instrumentation) monkeypatch.setattr(harness.time, "perf_counter", clock) monkeypatch.setitem( - scoring.SCORERS, "r2", replace(original, evaluate=score) + scoring.SCORERS, "r2", replace(original, callback=score) ) result = _benchmark(case) assert events.count("score") == (1 if failure else 2) @@ -3446,7 +3514,7 @@ def test_r2_constant_targets(force_finite): case = resolve_case(_scored_request(), PROFILE) parameters = {} if force_finite is None else {"force_finite": force_finite} spec = replace(case.scoring, parameters=parameters) - kwargs = dict( + context = EvaluationContext( estimator=None, output=np.zeros(32), X=None, @@ -3455,23 +3523,23 @@ def test_r2_constant_targets(force_finite): ) with np.errstate(divide="ignore", invalid="ignore"): if force_finite is True: - assert scoring.evaluate(spec, **kwargs)[0]["value"] == 0 + assert scoring.evaluate(spec, context)[0]["value"] == 0 else: with pytest.raises(ValueError, match="nonfinite"): - scoring.evaluate(spec, **kwargs) + scoring.evaluate(spec, context) @pytest.mark.parametrize("value", [float("nan"), float("inf"), -float("inf")]) def test_nonfinite_scoring_results_fail_case(monkeypatch, value): original = scoring.SCORERS["r2"] - def score(**kwargs): - metrics = original.evaluate(**kwargs) + def score(context, parameters): + metrics = original.callback(context, parameters) metrics[0]["value"] = value return metrics monkeypatch.setitem( - scoring.SCORERS, "r2", replace(original, evaluate=score) + scoring.SCORERS, "r2", replace(original, callback=score) ) result = _benchmark(resolve_case(_scored_request(), PROFILE)) assert result["outcome"]["last_phase"] == "scoring" @@ -3553,7 +3621,10 @@ def predict(self, X): "estimator,scorer,parameters,dataset", [ ("PCA", "reconstruction", {"n_components": 2}, "blobs"), + ("PCA", "reconstruction", {"n_components": 2}, "matrix"), ("TruncatedSVD", "reconstruction", {"n_components": 2}, "blobs"), + ("PCA", "trustworthiness", {"n_components": 2}, "blobs"), + ("KernelDensity", "log_density", {}, "blobs"), ( "GaussianRandomProjection", "distance_distortion", @@ -3588,32 +3659,119 @@ def test_scorer_provider_integration( assert np.isfinite(metric["value"]) -@pytest.mark.parametrize("provider", ["scikit-learn", "cuml", "cuml.dask"]) -def test_covariance_metric_matches_analytic_density(provider): +def test_covariance_metric_matches_analytic_density(): from cuml.benchmark.metrics import covariance - estimator = SimpleNamespace(covariance_=np.eye(2), location_=np.zeros(2)) expected = -np.log(2 * np.pi) - 0.5 actual = covariance( - estimator=estimator, - X=get_provider(provider).backend.convert_data( - np.array([[1.0, 0.0], [0.0, 1.0]]), representation="array" - ), + X=np.array([[1.0, 0.0], [0.0, 1.0]]), + covariance=np.eye(2), + location=np.zeros(2), parameters={}, ) assert actual[0]["value"] == pytest.approx(expected) -@pytest.mark.parametrize("provider", ["scikit-learn", "cuml", "cuml.dask"]) -def test_projection_metric_preserves_distances(provider): +@pytest.mark.parametrize("sparse_input", [False, True]) +def test_projection_metric_preserves_distances(sparse_input): from cuml.benchmark.metrics import projection X = np.random.default_rng(42).normal(size=(32, 4)) actual = projection( - estimator=SimpleNamespace(transform=lambda X: X), - X=get_provider(provider).backend.convert_data( - X, representation="array" - ), + X=sparse.csr_matrix(X) if sparse_input else X, + Z=X, parameters={"pairs": 100}, ) assert actual[0]["value"] == pytest.approx(0) + + +@pytest.mark.parametrize("provider", ["scikit-learn", "cuml", "cuml.dask"]) +@pytest.mark.parametrize( + "name,metric_name,input_names", + [ + ("accuracy", "accuracy", {"y", "prediction"}), + ("r2", "r2", {"y", "prediction"}), + ("adjusted_rand", "adjusted_rand", {"y", "prediction"}), + ("reconstruction", "reconstruction", {"X", "reconstructed"}), + ("distance_distortion", "projection", {"X", "Z"}), + ("trustworthiness", "trustworthiness", {"X", "Z"}), + ( + "gaussian_log_likelihood", + "covariance", + {"X", "covariance", "location"}, + ), + ("log_density", "density", {"log_density"}), + ], +) +@pytest.mark.parametrize("operation", ["fit", "predict"]) +def test_scoring_metrics_receive_only_host_inputs( + monkeypatch, provider, name, metric_name, input_names, operation +): + from cuml.benchmark import metrics + + backend = get_provider(provider).backend + + def convert(value): + return backend.convert_data(value, representation="array") + + X = convert(np.random.default_rng(42).normal(size=(32, 4))) + y = np.arange(32) % 2 + prediction = convert(y) + log_density = convert(np.full(32, -1.0)) + calls = [] + + def predict(inputs): + assert inputs is X + calls.append("predict") + return prediction + + def transform(inputs): + assert inputs is X + calls.append("transform") + return X + + def inverse_transform(inputs): + assert inputs is X + calls.append("inverse_transform") + return X + + def score_samples(inputs): + assert inputs is X + calls.append("score_samples") + return log_density + + estimator = SimpleNamespace( + predict=predict, + transform=transform, + inverse_transform=inverse_transform, + score_samples=score_samples, + covariance_=convert(np.eye(4)), + location_=convert(np.zeros(4)), + ) + original = getattr(metrics, metric_name) + received = [] + + def host_metric(*, parameters, **inputs): + assert set(inputs) == input_names + assert all(isinstance(value, np.ndarray) for value in inputs.values()) + received.append(inputs) + return original(**inputs, parameters=parameters) + + monkeypatch.setattr(metrics, metric_name, host_metric) + result = scoring.evaluate( + scoring.ScoringSpec(name, {}, 32), + EvaluationContext(estimator, X, y, prediction, operation), + ) + assert len(received) == 1 + assert np.isfinite(result[0]["value"]) + if "prediction" in input_names: + assert calls == ([] if operation == "predict" else ["predict"]) + np.testing.assert_array_equal(received[0]["prediction"], y) + elif name == "reconstruction": + assert calls == ["transform", "inverse_transform"] + elif "Z" in input_names: + assert calls == ["transform"] + elif name == "log_density": + assert calls == ["score_samples"] + else: + assert calls == [] From 1ad7b25ed42011519ddd0c1b7c307e89a14fb1ad Mon Sep 17 00:00:00 2001 From: Simon Adorf Date: Thu, 12 Nov 2026 17:03:53 -0600 Subject: [PATCH 4/4] Remove redundant unscored benchmark comments --- .../cuml/benchmark/suites/estimators.yaml | 64 ------------------- 1 file changed, 64 deletions(-) diff --git a/python/cuml/cuml/benchmark/suites/estimators.yaml b/python/cuml/cuml/benchmark/suites/estimators.yaml index 89c6c1f037..1e95f304d6 100644 --- a/python/cuml/cuml/benchmark/suites/estimators.yaml +++ b/python/cuml/cuml/benchmark/suites/estimators.yaml @@ -395,7 +395,6 @@ cases: n_clusters: 8 metric: euclidean linkage: single - # Unscored: no common held-out evaluation in this configuration. - estimator: AgglomerativeClustering tags: [balanced] @@ -413,7 +412,6 @@ cases: n_clusters: 8 metric: euclidean linkage: single - # Unscored: no common held-out evaluation in this configuration. - estimator: AgglomerativeClustering tags: [wide] @@ -431,7 +429,6 @@ cases: n_clusters: 8 metric: euclidean linkage: single - # Unscored: no common held-out evaluation in this configuration. - estimator: SpectralClustering tags: [thin] @@ -451,7 +448,6 @@ cases: n_neighbors: 10 n_init: 1 random_state: 42 - # Unscored: no common held-out evaluation in this configuration. - estimator: SpectralClustering tags: [balanced] @@ -471,7 +467,6 @@ cases: n_neighbors: 10 n_init: 1 random_state: 42 - # Unscored: no common held-out evaluation in this configuration. - estimator: SpectralClustering tags: [wide] @@ -491,7 +486,6 @@ cases: n_neighbors: 10 n_init: 1 random_state: 42 - # Unscored: no common held-out evaluation in this configuration. - estimator: NearestNeighbors tags: [thin] @@ -509,7 +503,6 @@ cases: fit_input_selection: [X] parameters: n_neighbors: 64 - # Unscored: reference-based scoring is not supported. - estimator: NearestNeighbors tags: [thin] @@ -529,7 +522,6 @@ cases: n_neighbors: 64 algorithm: brute n_jobs: -1 - # Unscored: reference-based scoring is not supported. - estimator: NearestNeighbors tags: [balanced] @@ -547,7 +539,6 @@ cases: fit_input_selection: [X] parameters: n_neighbors: 64 - # Unscored: reference-based scoring is not supported. - estimator: NearestNeighbors tags: [balanced] @@ -567,7 +558,6 @@ cases: n_neighbors: 64 algorithm: brute n_jobs: -1 - # Unscored: reference-based scoring is not supported. - estimator: NearestNeighbors tags: [wide] @@ -585,7 +575,6 @@ cases: fit_input_selection: [X] parameters: n_neighbors: 64 - # Unscored: reference-based scoring is not supported. - estimator: NearestNeighbors tags: [wide] @@ -605,7 +594,6 @@ cases: n_neighbors: 64 algorithm: brute n_jobs: -1 - # Unscored: reference-based scoring is not supported. - estimator: PCA tags: [thin] @@ -1528,7 +1516,6 @@ cases: parameters: eps: 3 min_samples: 2 - # Unscored: no common held-out evaluation in this configuration. - estimator: DBSCAN tags: [thin] @@ -1546,7 +1533,6 @@ cases: eps: 3 min_samples: 2 algorithm: brute - # Unscored: no common held-out evaluation in this configuration. - estimator: DBSCAN tags: [balanced] @@ -1563,7 +1549,6 @@ cases: parameters: eps: 3 min_samples: 2 - # Unscored: no common held-out evaluation in this configuration. - estimator: DBSCAN tags: [balanced] @@ -1581,7 +1566,6 @@ cases: eps: 3 min_samples: 2 algorithm: brute - # Unscored: no common held-out evaluation in this configuration. - estimator: DBSCAN tags: [wide] @@ -1598,7 +1582,6 @@ cases: parameters: eps: 3 min_samples: 2 - # Unscored: no common held-out evaluation in this configuration. - estimator: DBSCAN tags: [wide] @@ -1616,7 +1599,6 @@ cases: eps: 3 min_samples: 2 algorithm: brute - # Unscored: no common held-out evaluation in this configuration. - estimator: KNeighborsClassifier tags: [thin] @@ -1751,7 +1733,6 @@ cases: operation: fit_transform input_selection: [X] parameters: {} - # Unscored: reference-based scoring is not supported. - estimator: StandardScaler tags: [balanced] @@ -1772,7 +1753,6 @@ cases: operation: fit_transform input_selection: [X] parameters: {} - # Unscored: reference-based scoring is not supported. - estimator: StandardScaler tags: [wide] @@ -1793,7 +1773,6 @@ cases: operation: fit_transform input_selection: [X] parameters: {} - # Unscored: reference-based scoring is not supported. - estimator: MinMaxScaler tags: [thin] @@ -1814,7 +1793,6 @@ cases: operation: fit_transform input_selection: [X] parameters: {} - # Unscored: reference-based scoring is not supported. - estimator: MinMaxScaler tags: [balanced] @@ -1835,7 +1813,6 @@ cases: operation: fit_transform input_selection: [X] parameters: {} - # Unscored: reference-based scoring is not supported. - estimator: MinMaxScaler tags: [wide] @@ -1856,7 +1833,6 @@ cases: operation: fit_transform input_selection: [X] parameters: {} - # Unscored: reference-based scoring is not supported. - estimator: MaxAbsScaler tags: [thin] @@ -1877,7 +1853,6 @@ cases: operation: fit_transform input_selection: [X] parameters: {} - # Unscored: reference-based scoring is not supported. - estimator: MaxAbsScaler tags: [balanced] @@ -1898,7 +1873,6 @@ cases: operation: fit_transform input_selection: [X] parameters: {} - # Unscored: reference-based scoring is not supported. - estimator: MaxAbsScaler tags: [wide] @@ -1919,7 +1893,6 @@ cases: operation: fit_transform input_selection: [X] parameters: {} - # Unscored: reference-based scoring is not supported. - estimator: Normalizer tags: [thin] @@ -1940,7 +1913,6 @@ cases: operation: fit_transform input_selection: [X] parameters: {} - # Unscored: reference-based scoring is not supported. - estimator: Normalizer tags: [balanced] @@ -1961,7 +1933,6 @@ cases: operation: fit_transform input_selection: [X] parameters: {} - # Unscored: reference-based scoring is not supported. - estimator: Normalizer tags: [wide] @@ -1982,7 +1953,6 @@ cases: operation: fit_transform input_selection: [X] parameters: {} - # Unscored: reference-based scoring is not supported. - estimator: RobustScaler tags: [thin] @@ -2003,7 +1973,6 @@ cases: operation: fit_transform input_selection: [X] parameters: {} - # Unscored: reference-based scoring is not supported. - estimator: RobustScaler tags: [balanced] @@ -2024,7 +1993,6 @@ cases: operation: fit_transform input_selection: [X] parameters: {} - # Unscored: reference-based scoring is not supported. - estimator: RobustScaler tags: [wide] @@ -2045,7 +2013,6 @@ cases: operation: fit_transform input_selection: [X] parameters: {} - # Unscored: reference-based scoring is not supported. - estimator: PolynomialFeatures tags: [thin] @@ -2067,7 +2034,6 @@ cases: input_selection: [X] parameters: degree: 2 - # Unscored: reference-based scoring is not supported. - estimator: PolynomialFeatures tags: [balanced] @@ -2089,7 +2055,6 @@ cases: input_selection: [X] parameters: degree: 2 - # Unscored: reference-based scoring is not supported. - estimator: PolynomialFeatures tags: [wide] @@ -2111,7 +2076,6 @@ cases: input_selection: [X] parameters: degree: 2 - # Unscored: reference-based scoring is not supported. - estimator: Binarizer tags: [thin] @@ -2132,7 +2096,6 @@ cases: operation: fit_transform input_selection: [X] parameters: {} - # Unscored: reference-based scoring is not supported. - estimator: Binarizer tags: [balanced] @@ -2153,7 +2116,6 @@ cases: operation: fit_transform input_selection: [X] parameters: {} - # Unscored: reference-based scoring is not supported. - estimator: Binarizer tags: [wide] @@ -2174,7 +2136,6 @@ cases: operation: fit_transform input_selection: [X] parameters: {} - # Unscored: reference-based scoring is not supported. - estimator: KBinsDiscretizer tags: [thin] @@ -2198,7 +2159,6 @@ cases: n_bins: 16 encode: ordinal strategy: uniform - # Unscored: reference-based scoring is not supported. - estimator: KBinsDiscretizer tags: [balanced] @@ -2222,7 +2182,6 @@ cases: n_bins: 16 encode: ordinal strategy: uniform - # Unscored: reference-based scoring is not supported. - estimator: KBinsDiscretizer tags: [wide] @@ -2246,7 +2205,6 @@ cases: n_bins: 16 encode: ordinal strategy: uniform - # Unscored: reference-based scoring is not supported. - estimator: PowerTransformer tags: [thin] @@ -2268,7 +2226,6 @@ cases: input_selection: [X] parameters: method: yeo-johnson - # Unscored: reference-based scoring is not supported. - estimator: PowerTransformer tags: [balanced] @@ -2290,7 +2247,6 @@ cases: input_selection: [X] parameters: method: yeo-johnson - # Unscored: reference-based scoring is not supported. - estimator: PowerTransformer tags: [wide] @@ -2312,7 +2268,6 @@ cases: input_selection: [X] parameters: method: yeo-johnson - # Unscored: reference-based scoring is not supported. - estimator: QuantileTransformer tags: [thin] @@ -2336,7 +2291,6 @@ cases: n_quantiles: 1000 subsample: 100000 random_state: 42 - # Unscored: reference-based scoring is not supported. - estimator: QuantileTransformer tags: [balanced] @@ -2360,7 +2314,6 @@ cases: n_quantiles: 1000 subsample: 100000 random_state: 42 - # Unscored: reference-based scoring is not supported. - estimator: QuantileTransformer tags: [wide] @@ -2384,7 +2337,6 @@ cases: n_quantiles: 1000 subsample: 100000 random_state: 42 - # Unscored: reference-based scoring is not supported. - estimator: LabelEncoder providers: [cuml, scikit-learn, cuml.accel, cuml.dask] @@ -2404,7 +2356,6 @@ cases: operation: fit_transform input_selection: [y] parameters: {} - # Unscored: reference-based scoring is not supported. - estimator: LabelEncoder providers: [cuml, scikit-learn, cuml.accel, cuml.dask] @@ -2424,7 +2375,6 @@ cases: operation: fit_transform input_selection: [y] parameters: {} - # Unscored: reference-based scoring is not supported. - estimator: LabelEncoder providers: [cuml, scikit-learn, cuml.accel, cuml.dask] @@ -2444,7 +2394,6 @@ cases: operation: fit_transform input_selection: [y] parameters: {} - # Unscored: reference-based scoring is not supported. - estimator: LabelBinarizer providers: [cuml, scikit-learn, cuml.accel, cuml.dask] @@ -2464,7 +2413,6 @@ cases: operation: fit_transform input_selection: [y] parameters: {} - # Unscored: reference-based scoring is not supported. - estimator: LabelBinarizer providers: [cuml, scikit-learn, cuml.accel, cuml.dask] @@ -2484,7 +2432,6 @@ cases: operation: fit_transform input_selection: [y] parameters: {} - # Unscored: reference-based scoring is not supported. - estimator: LabelBinarizer providers: [cuml, scikit-learn, cuml.accel, cuml.dask] @@ -2504,7 +2451,6 @@ cases: operation: fit_transform input_selection: [y] parameters: {} - # Unscored: reference-based scoring is not supported. - estimator: TSNE tags: [thin] @@ -2519,7 +2465,6 @@ cases: operation: fit input_selection: [X] parameters: {} - # Unscored: no common held-out evaluation in this configuration. - estimator: TSNE tags: [balanced] @@ -2534,7 +2479,6 @@ cases: operation: fit input_selection: [X] parameters: {} - # Unscored: no common held-out evaluation in this configuration. - estimator: TSNE tags: [wide] @@ -2549,7 +2493,6 @@ cases: operation: fit input_selection: [X] parameters: {} - # Unscored: no common held-out evaluation in this configuration. - estimator: MultinomialNB tags: [thin] @@ -2681,7 +2624,6 @@ cases: input_selection: [X] parameters: n_neighbors: 20 - # Unscored: no common held-out evaluation in this configuration. - estimator: BernoulliNB providers: [cuml] @@ -2747,7 +2689,6 @@ cases: parameters: smooth: 0.0 seed: 42 - # Unscored: reference-based scoring is not supported. - estimator: TargetEncoder providers: [cuml.accel] @@ -2766,7 +2707,6 @@ cases: parameters: smooth: 0.0 random_state: 42 - # Unscored: reference-based scoring is not supported. - estimator: OneHotEncoder providers: [cuml, cuml.accel, cuml.dask] @@ -2785,7 +2725,6 @@ cases: parameters: sparse_output: false handle_unknown: ignore - # Unscored: reference-based scoring is not supported. - estimator: OrdinalEncoder providers: [cuml, cuml.accel, cuml.dask] @@ -2802,7 +2741,6 @@ cases: operation: fit_transform input_selection: [X] parameters: {} - # Unscored: held-out rows may contain unknown categories. - estimator: SpectralEmbedding providers: [cuml, scikit-learn, cuml.accel] @@ -2817,7 +2755,6 @@ cases: n_components: 2 n_neighbors: 10 random_state: 42 - # Unscored: no common held-out evaluation in this configuration. - estimator: UMAP providers: [cuml, umap-learn, cuml.accel] @@ -2845,4 +2782,3 @@ cases: input_selection: [X] parameters: min_cluster_size: 5 - # Unscored: no common held-out evaluation in this configuration.