Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions docs/source/developer_guide/benchmarking.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 9 additions & 0 deletions python/cuml/cuml/benchmark/_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,14 @@ class DatasetManifest(msgspec.Struct, forbid_unknown_fields=True):
format: Literal["dense", "csr"] = "dense"


class ScoringManifest(msgspec.Struct, forbid_unknown_fields=True):
"""Select a registered quality scorer and optional held-out fitting size."""

name: NonEmptyString
parameters: dict[str, Any] = msgspec.field(default_factory=dict)
evaluation_rows: PositiveCount | None = None


class CaseManifest(msgspec.Struct, forbid_unknown_fields=True):
"""Specify an estimator operation and its dataset inputs."""

Expand All @@ -57,6 +65,7 @@ class CaseManifest(msgspec.Struct, forbid_unknown_fields=True):
# Omission inherits the suite providers; a list narrows applicability.
providers: Providers | None = None
tags: list[str] = msgspec.field(default_factory=list)
scoring: ScoringManifest | None = None
# Required for inference, forbidden for fitting (validated by the loader).
fit_input_selection: InputSelection | None = None
# Omission inherits the profile timeout; explicit null disables it.
Expand Down
14 changes: 11 additions & 3 deletions python/cuml/cuml/benchmark/_selection.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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

Expand Down
43 changes: 42 additions & 1 deletion python/cuml/cuml/benchmark/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import argparse
import contextlib
import datetime as dt
import json
import logging
import re
import sys
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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.

Expand All @@ -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):
Expand Down
Loading
Loading