diff --git a/docs/source/developer_guide/benchmarking.md b/docs/source/developer_guide/benchmarking.md index ee301f35d0..b905505418 100644 --- a/docs/source/developer_guide/benchmarking.md +++ b/docs/source/developer_guide/benchmarking.md @@ -216,6 +216,40 @@ 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`. +## 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. + +Compare saved scores with +`python -m cuml.benchmark compare baseline/cuml.json candidate/cuml.json`; +add `--format json` for machine-readable output. Comparison is read-only and +reports score summaries and gaps to the best complete mean for compatible +workloads. Use `-k 'PCA or UMAP'` to filter recorded workloads with the same +keyword expressions used for benchmark selection. + ## 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/_selection.py b/python/cuml/cuml/benchmark/_selection.py index 803a402c97..02e168038c 100644 --- a/python/cuml/cuml/benchmark/_selection.py +++ b/python/cuml/cuml/benchmark/_selection.py @@ -35,6 +35,14 @@ def case_keywords(case: ResolvedCase) -> tuple[str, ...]: def compile_expression(expression: str) -> Callable[[ResolvedCase], bool]: + """Compile a keyword expression for resolved benchmark cases.""" + matches = compile_keyword_expression(expression) + return lambda case: matches(case_keywords(case)) + + +def compile_keyword_expression( + expression: str, +) -> Callable[[tuple[str, ...]], bool]: """Parse substring terms, parentheses, and lowercase not/and/or operators.""" tokens = re.findall(r"\(|\)|[^\s()]+", expression) position = 0 @@ -95,7 +103,7 @@ def disjunction() -> Node: return ("or", nodes) if not tokens: - return lambda case: True + return lambda keywords: True try: tree = disjunction() except RecursionError as exc: @@ -111,8 +119,8 @@ def evaluate(node: Node, keywords: tuple[str, ...]) -> bool: values = (evaluate(child, keywords) for child in node[1]) return all(values) if node[0] == "and" else any(values) - def matches(case: ResolvedCase) -> bool: - return evaluate(tree, tuple(k.casefold() for k in case_keywords(case))) + def matches(keywords: tuple[str, ...]) -> bool: + return evaluate(tree, tuple(k.casefold() for k in keywords)) return matches diff --git a/python/cuml/cuml/benchmark/cli.py b/python/cuml/cuml/benchmark/cli.py index fe625dfeb1..8e379c0bdb 100644 --- a/python/cuml/cuml/benchmark/cli.py +++ b/python/cuml/cuml/benchmark/cli.py @@ -8,6 +8,7 @@ import argparse import contextlib import datetime as dt +import json import logging import re import sys @@ -47,7 +48,8 @@ def _parser( parser = argparse.ArgumentParser( prog=" ".join(_entrypoint()) if __package__ == "benchmark" - else "python -m cuml.benchmark" + else "python -m cuml.benchmark", + epilog="Use 'compare FILE FILE ...' to compare recorded quality metrics.", ) parser.add_argument( "--suite", @@ -211,6 +213,43 @@ def _collect(plan, selected, expression: str) -> None: ) +def _compare_main(argv: list[str]) -> int: + """Compare saved artifacts without loading suites or preparing providers.""" + from .comparison import compare, render_table + + parser = argparse.ArgumentParser(prog=" ".join(_entrypoint()) + " compare") + parser.add_argument( + "artifacts", + nargs="+", + help="provider artifact JSON files (at least two)", + ) + parser.add_argument("--format", choices=["table", "json"], default="table") + parser.add_argument( + "-k", + default="", + metavar="EXPRESSION", + help="filter recorded workloads using benchmark keyword expressions", + ) + args = parser.parse_args(argv) + if len(args.artifacts) < 2: + parser.error("compare requires at least two artifact files") + try: + report = compare(args.artifacts, keyword_expression=args.k) + except ValueError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + if args.format == "json": + print(json.dumps(report, indent=2, allow_nan=False)) + else: + from rich.console import Console + + Console().print(render_table(report)) + if not report["comparable_metrics"]: + print("No comparable quality metrics found.", file=sys.stderr) + return 1 + return 0 + + def main(argv: list[str] | None = None) -> int: """Run the benchmark command and return its exit status. @@ -220,6 +259,8 @@ def main(argv: list[str] | None = None) -> int: Command arguments; defaults to sys.argv[1:]. """ argument_values = sys.argv[1:] if argv is None else argv + if argument_values and argument_values[0] == "compare": + return _compare_main(argument_values[1:]) parser = _suite_aware_parser(argument_values) args = parser.parse_args(argument_values) if args.collect_only and (args.resume or args._worker): diff --git a/python/cuml/cuml/benchmark/comparison.py b/python/cuml/cuml/benchmark/comparison.py new file mode 100644 index 0000000000..54c0f0f51f --- /dev/null +++ b/python/cuml/cuml/benchmark/comparison.py @@ -0,0 +1,494 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Read-only comparison of quality metrics in recorded benchmark artifacts.""" + +from __future__ import annotations + +import json +import math +from collections import Counter +from pathlib import Path +from statistics import mean +from typing import Any + +from ._selection import compile_keyword_expression +from .suite import Workload + +EXTENSION = "com.nvidia.cuml.benchmark" + + +def _load(path): + """Read a schema-v2 artifact and reject ambiguous workload identities.""" + + def reject_constant(value): + raise ValueError(f"nonfinite JSON number: {value}") + + artifact = json.loads( + Path(path).read_text(), parse_constant=reject_constant + ) + if artifact["schema_version"] != 2: + raise ValueError("unsupported artifact schema version") + ids = set() + for result in artifact["results"]: + identity = result["id"] + if ( + identity in ids + or Workload.from_artifact_fields(result).digest() != identity + ): + raise ValueError("duplicate or inconsistent workload identity") + ids.add(identity) + return artifact + + +def _summary(result, artifact, name): + """Summarize successful measurements; incomplete cases remain unranked.""" + summary = dict( + status="missing_case", + valid=0, + expected=None, + mean=None, + min=None, + max=None, + gap_to_best=None, + best=False, + ) + if result is None: + return summary + descriptor = result["extensions"].get(EXTENSION, {}).get("scoring") + plan = artifact["run"]["extensions"][EXTENSION].get("execution_plan", []) + entries = [ + item for item in plan if item["case_label"] == result["case_label"] + ] + if len(entries) > 1: + raise ValueError("duplicate case in execution plan") + summary["expected"] = entries[0]["repetitions"] if entries else None + if summary["expected"] is not None and ( + type(summary["expected"]) is not int or summary["expected"] < 1 + ): + raise ValueError("invalid repetition count") + if descriptor is not None: + for key in ("name", "version", "population", "partition"): + if not isinstance(descriptor[key], str) or not descriptor[key]: + raise ValueError("invalid scoring descriptor") + if ( + type(descriptor["evaluation_rows"]) is not int + or descriptor["evaluation_rows"] < 1 + or not isinstance(descriptor["parameters"], dict) + ): + raise ValueError("invalid scoring descriptor") + summary["scoring"] = descriptor + summary["case_outcome"] = result["outcome"] + values, definitions = [], [] + observation_ids = set() + for observation in result["observations"]: + if observation["id"] in observation_ids: + raise ValueError("duplicate observation identity") + observation_ids.add(observation["id"]) + if ( + observation["role"] != "measurement" + or observation["outcome"]["status"] != "success" + ): + continue + matches = [ + metric + for metric in observation["metrics"] + if metric["name"] == name + ] + if len(matches) > 1: + raise ValueError("duplicate metric in observation") + for metric in matches: + value = metric["value"] + if isinstance(value, bool) or not math.isfinite(value): + raise ValueError("invalid recorded metric value") + if metric["direction"] not in { + "higher_is_better", + "lower_is_better", + "neutral", + }: + raise ValueError("invalid metric direction") + values.append(value) + definitions.append( + dict( + scoring=descriptor, + unit=metric["unit"], + direction=metric["direction"], + ) + ) + if not values: + summary["status"] = ( + "unscored" if descriptor is None else "no_valid_scores" + ) + return summary + summary.update( + valid=len(values), + mean=mean(values), + min=min(values), + max=max(values), + definition=definitions[0], + ) + if ( + descriptor is None + or any(item != definitions[0] for item in definitions) + or (entries and entries[0].get("scoring") != descriptor) + ): + summary["status"] = "incompatible_scoring" + else: + summary["status"] = ( + "complete" + if len(values) == summary["expected"] + and result["outcome"]["status"] == "success" + else "partial" + ) + return summary + + +def compare( + paths: list[str | Path], *, keyword_expression: str = "" +) -> dict[str, Any]: + """Compare matching workload/scorer metrics against the best complete mean. + + Each file is a separate experiment, including files from the same provider. + Only successful, complete cases with matching scoring descriptors, metric + units/directions, and run methodology participate in comparisons. Warmups + are excluded; partial, missing, and incompatible results remain visible. + """ + if len(paths) < 2: + raise ValueError("compare requires at least two artifact files") + artifacts = [] + for path in paths: + try: + artifacts.append(_load(path)) + except (OSError, ValueError, KeyError, TypeError) as exc: + raise ValueError(f"unable to read artifact {path}: {exc}") from exc + try: + return _compare(paths, artifacts, keyword_expression) + except (KeyError, TypeError, ValueError, OverflowError) as exc: + raise ValueError(f"invalid comparison data: {exc}") from exc + + +def _compare(paths, artifacts, keyword_expression): + providers = [ + a["run"]["extensions"][EXTENSION]["provider"] for a in artifacts + ] + counts = Counter(providers) + labels = [ + f"{provider} [{index + 1}]" if counts[provider] > 1 else provider + for index, provider in enumerate(providers) + ] + inputs = [ + dict( + label=label, + path=str(path), + provider=provider, + run_id=a["run"]["id"], + system=a["run"]["system"], + software=a["run"]["software"], + methodology=a["run"]["methodology"], + ) + for label, path, provider, a in zip( + labels, paths, providers, artifacts, strict=True + ) + ] + indexed = [{r["id"]: r for r in a["results"]} for a in artifacts] + rows, comparable = [], 0 + workloads = { + result["id"]: result + for artifact in artifacts + for result in artifact["results"] + } + + def workload_order(identity): + result = workloads[identity] + dimensions = { + dimension["name"]: dimension["size"] + for dimension in result["input"]["dimensions"] + } + return ( + result["algorithm"], + result["operation"]["name"], + dimensions.get("rows", 0), + dimensions.get("features", 0), + identity, + ) + + matches = compile_keyword_expression(keyword_expression) + selected = [] + for identity, result in workloads.items(): + keywords = ( + result["algorithm"], + result["operation"]["name"], + f"{result['algorithm']}.{result['operation']['name']}", + result["dataset"]["name"], + result["case_label"], + identity, + *( + f"{dimension['name']}={dimension['size']}" + for dimension in result["input"]["dimensions"] + ), + f"dtype={result['input']['data_type']}", + ) + if matches(keywords): + selected.append(identity) + if keyword_expression and not selected: + raise ValueError(f"no benchmark cases match -k {keyword_expression!r}") + + for identity in sorted(selected, key=workload_order): + results = [index.get(identity) for index in indexed] + exemplar = next(r for r in results if r is not None) + names = sorted( + { + m["name"] + for r in results + if r is not None + for o in r["observations"] + if o["role"] == "measurement" + for m in o["metrics"] + } + ) + for name in names or [None]: + summaries = [ + _summary(r, a, name) + for r, a in zip(results, artifacts, strict=True) + ] + valid = [ + (s, a["run"]["methodology"]) + for s, a in zip(summaries, artifacts, strict=True) + if s["valid"] + ] + compatible = bool(valid) and all( + s["status"] != "incompatible_scoring" + and s["definition"] == valid[0][0]["definition"] + and methodology == valid[0][1] + for s, methodology in valid + ) + if compatible: + complete = [s for s, _ in valid if s["status"] == "complete"] + comparable += len(complete) * (len(complete) - 1) // 2 + direction = valid[0][0]["definition"]["direction"] + if len(complete) >= 2 and direction != "neutral": + best = (max if direction == "higher_is_better" else min)( + s["mean"] for s in complete + ) + for s in complete: + s["best"] = s["mean"] == best + s["gap_to_best"] = ( + best - s["mean"] + if direction == "higher_is_better" + else s["mean"] - best + ) + else: + for s, _ in valid: + s["status"] = "incompatible_scoring" + rows.append( + dict( + workload_id=identity, + algorithm=exemplar["algorithm"], + operation=exemplar["operation"]["name"], + dimensions=exemplar["input"]["dimensions"], + metric=name, + artifacts={ + label: summary + for label, summary, result, artifact in zip( + labels, summaries, results, artifacts, strict=True + ) + if result is not None + or "execution_plan" + not in artifact["run"]["extensions"][EXTENSION] + or any( + item["case_label"] == exemplar["case_label"] + for item in artifact["run"]["extensions"][ + EXTENSION + ]["execution_plan"] + ) + }, + ) + ) + return dict( + baseline="best_complete_mean", + keyword_expression=keyword_expression, + inputs=inputs, + comparable_metrics=comparable, + rows=rows, + ) + + +def render_table(report): + """Group metrics by workload, with direction-aware colors and literal text.""" + from rich import box + from rich.console import Group + from rich.panel import Panel + from rich.table import Table + from rich.text import Text + + renderables = [] + inputs = Table(box=box.SIMPLE, padding=(0, 1), expand=True) + inputs.add_column("Artifact", style="cyan", no_wrap=True) + inputs.add_column("File", overflow="fold") + inputs.add_column("Run", style="dim", overflow="fold") + for item in report["inputs"]: + inputs.add_row( + *(Text(item[key]) for key in ("label", "path", "run_id")) + ) + renderables.append( + Panel(inputs, title="Benchmark comparison", border_style="cyan") + ) + if report["keyword_expression"]: + renderables.append( + Text(f"Selection: {report['keyword_expression']}", style="dim") + ) + differing_fields = [ + field + for field in ("system", "software", "methodology") + if any( + item[field] != report["inputs"][0][field] + for item in report["inputs"][1:] + ) + ] + environment_fields = [ + field for field in differing_fields if field != "methodology" + ] + if environment_fields: + renderables.append( + Text( + f"Note: {' and '.join(environment_fields)} metadata differs. " + "These environment differences do not prevent score comparison; " + "see JSON input metadata for details.", + style="yellow", + ) + ) + if "methodology" in differing_fields: + renderables.append( + Text( + "Warning: run methodology differs. Scores from differing " + "methodologies are incompatible and are not ranked together; " + "see JSON input metadata for details.", + style="red", + ) + ) + workload_tables = [] + widths = [ + Text(header).cell_len + for header in ( + "Artifact", + "Scored/expected", + "Mean", + "Min", + "Max", + "Gap", + "Status", + ) + ] + for row in report["rows"]: + heading = Text( + f"\n{row['algorithm']}.{row['operation']}", style="bold cyan" + ) + shape = " × ".join(str(d["size"]) for d in row["dimensions"]) + heading.append( + f" {shape} · {row['workload_id'][7:19]}", style="dim" + ) + heading.append(f" · {row['metric'] or 'no metrics'}", style="bold") + renderables.append(heading) + table = Table( + box=box.ROUNDED, + header_style="bold", + border_style="dim", + padding=(0, 1), + expand=True, + ) + table.add_column("Artifact", style="cyan", overflow="fold") + for column in ("Scored/expected", "Mean", "Min", "Max", "Gap"): + table.add_column(column, justify="right") + table.add_column("Status", overflow="fold") + ranked = sorted( + ( + (label, summary) + for label, summary in row["artifacts"].items() + if summary["gap_to_best"] is not None + ), + key=lambda item: item[1]["gap_to_best"], + ) + unranked = [ + (label, summary) + for label, summary in row["artifacts"].items() + if summary["gap_to_best"] is None + ] + for label, summary in [*ranked, *unranked]: + values = [ + Text("—", style="dim") + if summary[key] is None + else Text(f"{summary[key]:.6g}") + for key in ("mean", "min", "max") + ] + gap = summary["gap_to_best"] + gap_text = Text("—", style="dim") + if gap is not None: + color = ( + "green" + if summary["best"] + else "yellow" + if math.isclose( + summary["mean"], + ranked[0][1]["mean"], + rel_tol=1e-6, + abs_tol=1e-8, + ) + else "red" + ) + gap_text = Text(f"{gap:.6g}", style=color) + status = summary["status"] + status_style = ( + "green" + if status == "complete" + else "red" + if status == "incompatible_scoring" + else "yellow" + ) + cells = ( + Text(label), + Text( + f"{summary['valid']}/{summary['expected'] if summary['expected'] is not None else '?'}" + ), + *values, + gap_text, + Text(status, style=status_style), + ) + widths = [ + max(width, cell.cell_len) + for width, cell in zip(widths, cells, strict=True) + ] + table.add_row(*cells, style="bold" if summary["best"] else None) + workload_tables.append(table) + renderables.append(table) + definition = next( + ( + s["definition"] + for s in row["artifacts"].values() + if "definition" in s + ), + None, + ) + if definition: + renderables.append( + Text( + f"{definition['unit']} · {definition['direction']} · Gap relative to best observed; zero is best", + style="dim", + ) + ) + # Use the same preferred widths for every table, including provider labels and + # scientific notation. Rich can shrink these uniformly for narrow consoles. + for table in workload_tables: + for column, width in zip(table.columns, widths, strict=True): + column.width = width + column.min_width = 1 + + footer = Text( + f"\nComparable metric pairs: {report['comparable_metrics']}", + style="bold", + ) + footer.append( + "\nBold rows indicate best observed complete results, including ties. Partial and neutral results are unranked.\nYellow: numerically close (rtol=1e-6, atol=1e-8).", + style="dim", + ) + renderables.append(footer) + return Group(*renderables) 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/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. 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 9626f1aa72..60119bce7d 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" @@ -3232,6 +3237,51 @@ def convert(value, *, representation): assert calls == [(value, representation)] +@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) @@ -3270,3 +3320,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) diff --git a/python/cuml/tests/test_benchmark_comparison.py b/python/cuml/tests/test_benchmark_comparison.py new file mode 100644 index 0000000000..b0de7e7a03 --- /dev/null +++ b/python/cuml/tests/test_benchmark_comparison.py @@ -0,0 +1,427 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Contract tests for read-only artifact comparison.""" + +import copy +import json + +import pytest + +from cuml.benchmark import cli, comparison, harness +from cuml.benchmark.suite import Suite, resolve_case + + +@pytest.fixture +def artifact(tmp_path): + case = resolve_case( + { + "estimator": "LinearRegression", + "operation": "fit", + "parameters": {}, + "input_selection": ["X", "y"], + "dataset": { + "generator": "regression", + "shape": {"rows": 64, "features": 4}, + }, + "scoring": {"name": "r2", "evaluation_rows": 32}, + }, + {"warmups": 1, "repetitions": 2, "size_scale": 1}, + ) + return harness.run_suite( + Suite("test", "test", "scikit-learn", "standard", (case,)), + tmp_path / "source.json", + ) + + +def write_pair(tmp_path, artifact, change=lambda a: None): + left, right = copy.deepcopy(artifact), copy.deepcopy(artifact) + measurements = [ + o + for o in right["results"][0]["observations"] + if o["role"] == "measurement" + ] + for observation in measurements: + observation["metrics"][0]["value"] = -0.5 + change(right) + paths = [tmp_path / "left.json", tmp_path / "right.json"] + for path, value in zip(paths, (left, right), strict=True): + path.write_text(json.dumps(value)) + return paths + + +@pytest.mark.parametrize( + "direction", ["higher_is_better", "lower_is_better", "neutral"] +) +def test_compare_ranking_and_read_only(tmp_path, artifact, direction): + for observation in artifact["results"][0]["observations"]: + for metric in observation["metrics"]: + metric["direction"] = direction + paths = write_pair(tmp_path, artifact) + original = [path.read_bytes() for path in paths] + report = comparison.compare(paths) + assert report["comparable_metrics"] == 1 + summaries = list(report["rows"][0]["artifacts"].values()) + assert len(report["inputs"]) == 2 + assert len({item["label"] for item in report["inputs"]}) == 2 + assert all(s["valid"] == s["expected"] == 2 for s in summaries) + assert all(s["status"] == "complete" for s in summaries) + if direction == "neutral": + assert all( + s["gap_to_best"] is None and not s["best"] for s in summaries + ) + else: + winner = 0 if direction == "higher_is_better" else 1 + assert summaries[winner]["best"] + assert summaries[winner]["gap_to_best"] == 0 + assert summaries[1 - winner]["gap_to_best"] == pytest.approx(1.5) + reversed_report = comparison.compare(paths[::-1]) + assert reversed_report["comparable_metrics"] == 1 + assert [path.read_bytes() for path in paths] == original + + +@pytest.mark.parametrize( + "change", ["version", "parameters", "unit", "direction", "methodology"] +) +def test_compare_incompatible_scoring(tmp_path, artifact, change): + def mutate(right): + result = right["results"][0] + if change in {"version", "parameters"}: + descriptor = result["extensions"][harness.EXTENSION]["scoring"] + descriptor[change] = ( + "different" if change == "version" else {"force_finite": True} + ) + right["run"]["extensions"][harness.EXTENSION]["execution_plan"][0][ + "scoring" + ] = copy.deepcopy(descriptor) + elif change == "methodology": + right["run"]["methodology"]["id"] = "different" + else: + for observation in result["observations"]: + for metric in observation["metrics"]: + metric[change] = ( + "different" if change == "unit" else "lower_is_better" + ) + + report = comparison.compare(write_pair(tmp_path, artifact, mutate)) + assert report["comparable_metrics"] == 0 + assert all( + s["status"] == "incompatible_scoring" and s["gap_to_best"] is None + for s in report["rows"][0]["artifacts"].values() + ) + + +@pytest.mark.parametrize( + "change,status", + [ + ("missing", "missing_case"), + ("partial", "partial"), + ("failed", "partial"), + ("unscored", "unscored"), + ("no_plan", "partial"), + ], +) +def test_compare_incomplete_results(tmp_path, artifact, change, status): + def mutate(right): + result = right["results"][0] + if change == "missing": + right["results"] = [] + elif change == "partial": + result["observations"].pop() + elif change == "failed": + result["outcome"] = {"status": "failed", "last_phase": "scoring"} + result["observations"][-1]["outcome"] = result["outcome"] + elif change == "no_plan": + right["run"]["extensions"][harness.EXTENSION].pop("execution_plan") + else: + result["extensions"][harness.EXTENSION].pop("scoring") + for observation in result["observations"]: + observation["metrics"] = [] + + report = comparison.compare(write_pair(tmp_path, artifact, mutate)) + assert report["comparable_metrics"] == 0 + summaries = list(report["rows"][0]["artifacts"].values()) + assert summaries[1]["status"] == status + assert all(s["gap_to_best"] is None for s in summaries) + + +def test_compare_excludes_warmups_and_marks_ties(tmp_path, artifact): + artifact["results"][0]["observations"][0]["metrics"] = [ + { + "name": "r2_score", + "value": -100, + "unit": "dimensionless", + "direction": "higher_is_better", + } + ] + + def tie(right): + right["results"] = copy.deepcopy(artifact["results"]) + + report = comparison.compare(write_pair(tmp_path, artifact, tie)) + assert all( + s["best"] and s["mean"] == pytest.approx(1) + for s in report["rows"][0]["artifacts"].values() + ) + + +@pytest.mark.parametrize( + "change", + [ + "duplicate_case", + "identity", + "nonfinite", + "duplicate_metric", + "duplicate_observation", + ], +) +def test_compare_rejects_invalid_artifacts(tmp_path, artifact, change): + def mutate(right): + result = right["results"][0] + if change == "duplicate_case": + right["results"].append(copy.deepcopy(result)) + elif change == "identity": + result["id"] = "sha256:wrong" + elif change == "nonfinite": + result["observations"][-1]["metrics"][0]["value"] = float("nan") + elif change == "duplicate_metric": + result["observations"][-1]["metrics"] *= 2 + else: + result["observations"].append( + copy.deepcopy(result["observations"][-1]) + ) + + with pytest.raises(ValueError): + comparison.compare(write_pair(tmp_path, artifact, mutate)) + + +def test_compare_workload_order(tmp_path, artifact): + from cuml.benchmark.suite import Workload + + combinations = [ + ("Ridge", "fit", 64, 4), + ("LinearRegression", "predict", 32, 4), + ("LinearRegression", "fit", 128, 4), + ("LinearRegression", "fit", 64, 8), + ("LinearRegression", "fit", 64, 4), + ] + original = artifact["results"][0] + artifact["results"] = [] + for algorithm, operation, rows, features in combinations: + result = copy.deepcopy(original) + result["algorithm"] = algorithm + result["operation"]["name"] = operation + result["input"]["dimensions"] = [ + {"name": "rows", "size": rows}, + {"name": "features", "size": features}, + ] + result["id"] = Workload.from_artifact_fields(result).digest() + artifact["results"].append(result) + paths = write_pair(tmp_path, artifact) + report = comparison.compare(paths) + actual = [ + ( + row["algorithm"], + row["operation"], + *(dimension["size"] for dimension in row["dimensions"]), + ) + for row in report["rows"] + ] + assert actual == sorted(combinations) + + +@pytest.mark.parametrize( + "expression", + [ + "linearregression", + "LinearRegression.fit", + "regression and not PCA", + "(PCA or LinearRegression) and rows=64 and features=4 and dtype=float32", + ], +) +def test_compare_keyword_selection(tmp_path, artifact, expression): + paths = write_pair(tmp_path, artifact) + report = comparison.compare(paths, keyword_expression=expression) + assert report["keyword_expression"] == expression + assert len(report["rows"]) == 1 + assert report["comparable_metrics"] == 1 + identity = artifact["results"][0]["id"] + assert ( + comparison.compare(paths, keyword_expression=identity)["rows"][0][ + "workload_id" + ] + == identity + ) + + +@pytest.mark.parametrize("expression", ["PCA", "and", "(regression"]) +def test_compare_keyword_errors(tmp_path, artifact, expression): + with pytest.raises(ValueError, match="-k"): + comparison.compare( + write_pair(tmp_path, artifact), keyword_expression=expression + ) + + +def test_compare_omits_workloads_not_in_provider_plan(tmp_path, artifact): + def mutate(right): + right["run"]["extensions"][harness.EXTENSION]["provider"] = ( + "umap-learn" + ) + right["run"]["extensions"][harness.EXTENSION]["execution_plan"] = [] + right["results"] = [] + + report = comparison.compare(write_pair(tmp_path, artifact, mutate)) + assert set(report["rows"][0]["artifacts"]) == {"scikit-learn"} + assert report["comparable_metrics"] == 0 + + +@pytest.mark.parametrize("direction", ["higher_is_better", "lower_is_better"]) +def test_compare_table_sorts_scores(tmp_path, artifact, direction): + from io import StringIO + + from rich.console import Console + + for observation in artifact["results"][0]["observations"]: + for metric in observation["metrics"]: + metric["direction"] = direction + paths = write_pair(tmp_path, artifact) + if direction == "higher_is_better": + paths.reverse() # Put the worse result first in both directions. + report = comparison.compare(paths) + output = StringIO() + Console(file=output, width=160).print(comparison.render_table(report)) + table = output.getvalue().split("LinearRegression.fit", 1)[1] + assert table.index("scikit-learn [2]") < table.index("scikit-learn [1]") + + +@pytest.mark.parametrize("direction", ["higher_is_better", "lower_is_better"]) +@pytest.mark.parametrize( + "best,gap,color", + [(1.0, 5e-7, "yellow"), (0.0, 5e-9, "yellow"), (1.0, 1e-4, "red")], +) +def test_compare_gap_numerical_tolerance( + tmp_path, artifact, direction, best, gap, color +): + from rich.table import Table + + for observation in artifact["results"][0]["observations"]: + for metric in observation["metrics"]: + metric["value"] = best + metric["direction"] = direction + + def mutate(right): + for observation in right["results"][0]["observations"]: + for metric in observation["metrics"]: + metric["value"] = ( + best - gap + if direction == "higher_is_better" + else best + gap + ) + + report = comparison.compare(write_pair(tmp_path, artifact, mutate)) + summaries = list(report["rows"][0]["artifacts"].values()) + assert summaries[0]["best"] + assert not summaries[1]["best"] + assert summaries[1]["gap_to_best"] == pytest.approx(gap) + table = next( + item + for item in comparison.render_table(report).renderables + if isinstance(item, Table) + ) + assert table.columns[5]._cells[0].style == "green" + assert table.columns[5]._cells[1].style == color + + +@pytest.mark.parametrize("width", [80, 160]) +def test_compare_tables_share_column_widths(tmp_path, artifact, width): + from io import StringIO + + from rich.console import Console + from rich.table import Table + + report = comparison.compare(write_pair(tmp_path, artifact)) + second = copy.deepcopy(report["rows"][0]) + second["artifacts"] = { + "long-provider-label": next(iter(second["artifacts"].values())) + } + second["artifacts"]["long-provider-label"]["mean"] = -123456.789 + report["rows"].append(second) + tables = [ + item + for item in comparison.render_table(report).renderables + if isinstance(item, Table) + ] + assert len(tables) == 2 + borders = [] + for table in tables: + output = StringIO() + Console(file=output, width=width).print(table) + borders.append( + next( + line + for line in output.getvalue().splitlines() + if line.startswith("╭") + ) + ) + assert borders[0] == borders[1] + + +def test_compare_grouped_colored_rendering(tmp_path, artifact): + from io import StringIO + + from rich.console import Console + + report = comparison.compare(write_pair(tmp_path, artifact)) + output = StringIO() + Console( + file=output, force_terminal=True, color_system="standard", width=160 + ).print(comparison.render_table(report)) + text = output.getvalue() + assert "Benchmark comparison" in text + assert "LinearRegression.fit" in text + from rich.table import Table + + table = next( + item + for item in comparison.render_table(report).renderables + if isinstance(item, Table) + ) + assert table.rows[0].style == "bold" + assert "higher_is_better" in text + assert "\x1b[32m" in text # Best gap / complete status. + assert "\x1b[31m" in text # Nonzero gap. + + +def test_compare_cli_no_execution(tmp_path, artifact, monkeypatch, capsys): + def forbidden(*args, **kwargs): + pytest.fail("comparison must not load suites or execute benchmarks") + + monkeypatch.setattr(cli, "_suite_aware_parser", forbidden) + paths = write_pair(tmp_path, artifact) + assert cli.main(["compare", *map(str, paths), "--format", "json"]) == 0 + assert json.loads(capsys.readouterr().out)["comparable_metrics"] == 1 + assert ( + cli.main( + [ + "compare", + *map(str, paths), + "-k", + "regression and rows=64", + "--format", + "json", + ] + ) + == 0 + ) + filtered = json.loads(capsys.readouterr().out) + assert filtered["keyword_expression"] == "regression and rows=64" + assert filtered["comparable_metrics"] == 1 + assert cli.main(["compare", *map(str, paths), "-k", "PCA"]) == 1 + assert "no benchmark cases match" in capsys.readouterr().err + assert cli.main(["compare", *map(str, paths)]) == 0 + assert "Gap" in capsys.readouterr().out + with pytest.raises(SystemExit) as exc: + cli.main(["compare", str(paths[0])]) + assert exc.value.code == 2 + paths[1].write_text("invalid") + assert cli.main(["compare", *map(str, paths)]) == 1