Skip to content
Draft
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Add optional held-out quality scoring to benchmark cases
  • Loading branch information
csadorf committed Nov 12, 2026
commit e03abfff44a9f126d5af2fe5f36d8ee889274a27
27 changes: 27 additions & 0 deletions docs/source/developer_guide/benchmarking.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 9 additions & 0 deletions python/cuml/cuml/benchmark/_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""

Expand All @@ -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.
Expand Down
33 changes: 33 additions & 0 deletions python/cuml/cuml/benchmark/datasets.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import importlib
import math
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
Expand Down Expand Up @@ -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.

Expand Down
92 changes: 72 additions & 20 deletions python/cuml/cuml/benchmark/harness.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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
],
Expand Down Expand Up @@ -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 {}
),
}
},
}
Expand All @@ -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(
Expand All @@ -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 = (
Expand All @@ -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,
)


Expand Down Expand Up @@ -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,
Expand All @@ -228,6 +257,7 @@ def _run_observation(
"metrics": [],
"extensions": dict(verification.extensions),
}
return observation, output


def _record_case_failure(
Expand Down Expand Up @@ -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,
Expand All @@ -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:
Expand Down
121 changes: 121 additions & 0 deletions python/cuml/cuml/benchmark/metrics.py
Original file line number Diff line number Diff line change
@@ -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",
)
Loading