diff --git a/docs/source/developer_guide/benchmarking.md b/docs/source/developer_guide/benchmarking.md index ee301f35d0..9ea52a4752 100644 --- a/docs/source/developer_guide/benchmarking.md +++ b/docs/source/developer_guide/benchmarking.md @@ -216,6 +216,24 @@ 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 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 ```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..ac39d350b0 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 DatasetPartitions: + """Store training, measured, and optional held-out evaluation populations. + + Measured data aliases training data for fitting operations and contains + disjoint rows for inference operations. + """ + + training: dict[str, Any] + measured: dict[str, Any] + evaluation: dict[str, Any] | None = None + + +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": + 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 DatasetPartitions(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..8d22200ab7 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, EvaluationContext, 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,30 @@ 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, + EvaluationContext( + 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..c12d26d0c1 --- /dev/null +++ b/python/cuml/cuml/benchmark/metrics.py @@ -0,0 +1,157 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""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 + +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): + """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): + """Compute Frobenius error normalized by the epsilon-bounded reference norm.""" + 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 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") + return metric( + "relative_reconstruction_error", + relative_error(reconstructed, X), + ) + + +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(Z).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(*, X, Z, parameters): + """Measure neighborhood preservation in a held-out embedding.""" + from sklearn.manifold import trustworthiness as score + + return metric( + "trustworthiness", + score(dense(X), dense(Z), **parameters), + higher=True, + ) + + +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(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") + 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(*, 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(log_density).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..0b747f2c17 --- /dev/null +++ b/python/cuml/cuml/benchmark/scoring.py @@ -0,0 +1,183 @@ +# 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 math +from dataclasses import dataclass +from typing import Any, Callable + +from . import metrics + + +@dataclass(frozen=True) +class EvaluationContext: + """Provide a fitted estimator, held-out data, and the measured output. + + ``X`` retains the provider's representation; ``y`` remains on the host. + Callbacks must preserve the estimator's fitted state. + """ + + 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: + """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 + + +@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 _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 _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 _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), + "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: + """Store a case's scorer, parameters, and evaluation population size.""" + + 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, + context: EvaluationContext, +) -> list[dict[str, Any]]: + """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") + return metrics diff --git a/python/cuml/cuml/benchmark/suite.py b/python/cuml/cuml/benchmark/suite.py index c7eb45a29b..1f68d88d12 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,40 @@ 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] + 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 +338,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/estimators.yaml b/python/cuml/cuml/benchmark/suites/estimators.yaml index 1fe8b3cd20..1e95f304d6 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] @@ -585,6 +609,7 @@ cases: input_selection: [X] parameters: n_components: 10 + scoring: {name: reconstruction, evaluation_rows: 4096} - estimator: PCA tags: [thin] @@ -600,6 +625,7 @@ cases: input_selection: [X] parameters: n_components: 25 + scoring: {name: reconstruction, evaluation_rows: 4096} - estimator: PCA tags: [balanced] @@ -615,6 +641,7 @@ cases: input_selection: [X] parameters: n_components: 10 + scoring: {name: reconstruction, evaluation_rows: 4096} - estimator: PCA tags: [balanced] @@ -630,6 +657,7 @@ cases: input_selection: [X] parameters: n_components: 25 + scoring: {name: reconstruction, evaluation_rows: 4096} - estimator: PCA tags: [wide] @@ -645,6 +673,7 @@ cases: input_selection: [X] parameters: n_components: 10 + scoring: {name: reconstruction, evaluation_rows: 4096} - estimator: PCA tags: [wide] @@ -660,6 +689,7 @@ cases: input_selection: [X] parameters: n_components: 25 + scoring: {name: reconstruction, evaluation_rows: 4096} - estimator: IncrementalPCA tags: [thin] @@ -675,6 +705,7 @@ cases: input_selection: [X] parameters: n_components: 10 + scoring: {name: reconstruction, evaluation_rows: 4096} - estimator: IncrementalPCA tags: [balanced] @@ -690,6 +721,7 @@ cases: input_selection: [X] parameters: n_components: 10 + scoring: {name: reconstruction, evaluation_rows: 4096} - estimator: IncrementalPCA tags: [wide] @@ -705,6 +737,7 @@ cases: input_selection: [X] parameters: n_components: 10 + scoring: {name: reconstruction, evaluation_rows: 4096} - estimator: TruncatedSVD tags: [thin] @@ -720,6 +753,7 @@ cases: input_selection: [X] parameters: n_components: 10 + scoring: {name: reconstruction, evaluation_rows: 4096} - estimator: TruncatedSVD tags: [balanced] @@ -735,6 +769,7 @@ cases: input_selection: [X] parameters: n_components: 10 + scoring: {name: reconstruction, evaluation_rows: 4096} - estimator: TruncatedSVD tags: [wide] @@ -750,6 +785,7 @@ cases: input_selection: [X] parameters: n_components: 10 + scoring: {name: reconstruction, evaluation_rows: 4096} - estimator: GaussianRandomProjection tags: [thin] @@ -765,6 +801,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 +817,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 +833,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 +849,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 +865,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 +881,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 +897,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 +913,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 +929,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 +945,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 +961,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 +977,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 +992,7 @@ cases: operation: fit input_selection: [X] parameters: {} + scoring: {name: gaussian_log_likelihood, evaluation_rows: 4096} - estimator: EmpiricalCovariance tags: [balanced] @@ -958,6 +1007,7 @@ cases: operation: fit input_selection: [X] parameters: {} + scoring: {name: gaussian_log_likelihood, evaluation_rows: 4096} - estimator: EmpiricalCovariance tags: [wide] @@ -972,6 +1022,7 @@ cases: operation: fit input_selection: [X] parameters: {} + scoring: {name: gaussian_log_likelihood, evaluation_rows: 4096} - estimator: LedoitWolf tags: [thin] @@ -986,6 +1037,7 @@ cases: operation: fit input_selection: [X] parameters: {} + scoring: {name: gaussian_log_likelihood, evaluation_rows: 4096} - estimator: LedoitWolf tags: [balanced] @@ -1000,6 +1052,7 @@ cases: operation: fit input_selection: [X] parameters: {} + scoring: {name: gaussian_log_likelihood, evaluation_rows: 4096} - estimator: LedoitWolf tags: [wide] @@ -1014,6 +1067,7 @@ cases: operation: fit input_selection: [X] parameters: {} + scoring: {name: gaussian_log_likelihood, evaluation_rows: 4096} - estimator: RandomForestClassifier tags: [thin] @@ -1035,6 +1089,7 @@ cases: input_selection: [X, y] parameters: n_estimators: 20 + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: RandomForestClassifier tags: [thin] @@ -1057,6 +1112,7 @@ cases: parameters: n_estimators: 20 n_jobs: -1 + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: RandomForestClassifier tags: [balanced] @@ -1078,6 +1134,7 @@ cases: input_selection: [X, y] parameters: n_estimators: 20 + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: RandomForestClassifier tags: [balanced] @@ -1100,6 +1157,7 @@ cases: parameters: n_estimators: 20 n_jobs: -1 + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: RandomForestClassifier tags: [wide] @@ -1121,6 +1179,7 @@ cases: input_selection: [X, y] parameters: n_estimators: 20 + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: RandomForestClassifier tags: [wide] @@ -1143,6 +1202,7 @@ cases: parameters: n_estimators: 20 n_jobs: -1 + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: RandomForestRegressor tags: [thin] @@ -1156,6 +1216,7 @@ cases: input_selection: [X, y] parameters: n_estimators: 20 + scoring: {name: r2, evaluation_rows: 4096} - estimator: RandomForestRegressor tags: [thin] @@ -1170,6 +1231,7 @@ cases: parameters: n_estimators: 20 n_jobs: -1 + scoring: {name: r2, evaluation_rows: 4096} - estimator: RandomForestRegressor tags: [balanced] @@ -1183,6 +1245,7 @@ cases: input_selection: [X, y] parameters: n_estimators: 20 + scoring: {name: r2, evaluation_rows: 4096} - estimator: RandomForestRegressor tags: [balanced] @@ -1197,6 +1260,7 @@ cases: parameters: n_estimators: 20 n_jobs: -1 + scoring: {name: r2, evaluation_rows: 4096} - estimator: RandomForestRegressor tags: [wide] @@ -1210,6 +1274,7 @@ cases: input_selection: [X, y] parameters: n_estimators: 20 + scoring: {name: r2, evaluation_rows: 4096} - estimator: RandomForestRegressor tags: [wide] @@ -1224,6 +1289,7 @@ cases: parameters: n_estimators: 20 n_jobs: -1 + scoring: {name: r2, evaluation_rows: 4096} - estimator: SVC tags: [thin] @@ -1245,6 +1311,7 @@ cases: input_selection: [X, y] parameters: kernel: rbf + scoring: {name: accuracy, evaluation_rows: 512} - estimator: SVC tags: [balanced] @@ -1266,6 +1333,7 @@ cases: input_selection: [X, y] parameters: kernel: rbf + scoring: {name: accuracy, evaluation_rows: 512} - estimator: SVC tags: [wide] @@ -1287,6 +1355,7 @@ cases: input_selection: [X, y] parameters: kernel: rbf + scoring: {name: accuracy, evaluation_rows: 512} - estimator: SVR tags: [thin] @@ -1300,6 +1369,7 @@ cases: input_selection: [X, y] parameters: kernel: rbf + scoring: {name: r2, evaluation_rows: 512} - estimator: SVR tags: [balanced] @@ -1313,6 +1383,7 @@ cases: input_selection: [X, y] parameters: kernel: rbf + scoring: {name: r2, evaluation_rows: 512} - estimator: SVR tags: [wide] @@ -1326,6 +1397,7 @@ cases: input_selection: [X, y] parameters: kernel: rbf + scoring: {name: r2, evaluation_rows: 512} - estimator: LinearSVC tags: [thin] @@ -1346,6 +1418,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: LinearSVC tags: [balanced] @@ -1366,6 +1439,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: LinearSVC tags: [wide] @@ -1386,6 +1460,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: LinearSVR tags: [thin] @@ -1398,6 +1473,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: r2, evaluation_rows: 4096} - estimator: LinearSVR tags: [balanced] @@ -1410,6 +1486,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: r2, evaluation_rows: 4096} - estimator: LinearSVR tags: [wide] @@ -1422,6 +1499,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: r2, evaluation_rows: 4096} - estimator: DBSCAN tags: [thin] @@ -1543,6 +1621,7 @@ cases: input_selection: [X] fit_input_selection: [X, y] parameters: {} + scoring: {name: accuracy} - estimator: KNeighborsClassifier tags: [balanced] @@ -1565,6 +1644,7 @@ cases: input_selection: [X] fit_input_selection: [X, y] parameters: {} + scoring: {name: accuracy} - estimator: KNeighborsClassifier tags: [wide] @@ -1587,6 +1667,7 @@ cases: input_selection: [X] fit_input_selection: [X, y] parameters: {} + scoring: {name: accuracy} - estimator: KNeighborsRegressor tags: [thin] @@ -1601,6 +1682,7 @@ cases: input_selection: [X] fit_input_selection: [X, y] parameters: {} + scoring: {name: r2} - estimator: KNeighborsRegressor tags: [balanced] @@ -1615,6 +1697,7 @@ cases: input_selection: [X] fit_input_selection: [X, y] parameters: {} + scoring: {name: r2} - estimator: KNeighborsRegressor tags: [wide] @@ -1629,6 +1712,7 @@ cases: input_selection: [X] fit_input_selection: [X, y] parameters: {} + scoring: {name: r2} - estimator: StandardScaler tags: [thin] @@ -2421,6 +2505,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: MultinomialNB tags: [balanced] @@ -2433,6 +2518,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: MultinomialNB tags: [wide] @@ -2445,6 +2531,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: GaussianNB tags: [thin] @@ -2465,6 +2552,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: GaussianNB tags: [balanced] @@ -2485,6 +2573,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: GaussianNB tags: [wide] @@ -2505,6 +2594,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: KernelDensity providers: [cuml, cuml.accel] @@ -2520,6 +2610,7 @@ cases: parameters: kernel: gaussian bandwidth: 1.0 + scoring: {name: log_density, evaluation_rows: 512} - estimator: LocalOutlierFactor providers: [cuml, scikit-learn] @@ -2547,6 +2638,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: ComplementNB providers: [cuml] @@ -2561,6 +2653,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: CategoricalNB providers: [cuml] @@ -2577,6 +2670,7 @@ cases: operation: fit input_selection: [X, y] parameters: {} + scoring: {name: accuracy, evaluation_rows: 4096} - estimator: TargetEncoder providers: [cuml] @@ -2675,6 +2769,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] 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..24cf70e655 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,10 +39,11 @@ 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 +from cuml.benchmark.scoring import EvaluationContext from cuml.benchmark.suite import ( BUILTIN_SUITES, Suite, @@ -1001,7 +1002,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 +1026,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 +1044,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 +1062,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 +3202,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 +3289,489 @@ 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") + + +@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", {}), + "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, + 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"] + 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": "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(context, parameters): + assert events[-3:] == ["clock", "clock", "exit"] + events.append("score") + if failure: + raise RuntimeError("evaluation failed") + return original.callback(context, parameters) + + monkeypatch.setattr(backend, "instrumentation", instrumentation) + monkeypatch.setattr(harness.time, "perf_counter", clock) + monkeypatch.setitem( + scoring.SCORERS, "r2", replace(original, callback=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) + context = EvaluationContext( + 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, context)[0]["value"] == 0 + else: + with pytest.raises(ValueError, match="nonfinite"): + 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(context, parameters): + metrics = original.callback(context, parameters) + metrics[0]["value"] = value + return metrics + + monkeypatch.setitem( + scoring.SCORERS, "r2", replace(original, callback=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"), + ("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", + {"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"]) + + +def test_covariance_metric_matches_analytic_density(): + from cuml.benchmark.metrics import covariance + + expected = -np.log(2 * np.pi) - 0.5 + actual = covariance( + 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("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( + 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 == []