Skip to content
Open
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
51 changes: 51 additions & 0 deletions docs/source/cli-benchmark.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,11 +118,20 @@ Benchmark a local kernel checkout (must contain `benchmarks/`):
kernels benchmark ./my_kernel
```

Benchmark a published kernel with local benchmark scripts, e.g. scripts that
are not on the Hub yet:

```bash
kernels benchmark kernels-community/activation@v1 --benchmarks ./activation/benchmarks
```

## Output

- By default, a table is printed (timings in ms).
- `--output <file>.jsonl` writes one record per workload as JSON Lines.
- `--json` prints the same records to stdout.
- `--push-to-hub <dataset>` pushes the records to a Hub dataset, see
[Pushing results to the Hub](#pushing-results-to-the-hub).

### Result records

Expand Down Expand Up @@ -204,6 +213,48 @@ power draw differ.
Use `--fail-on-regression` to exit with a non-zero status when any workload got
slower, which is useful in CI.

## Pushing results to the Hub

Push the results of a run to a Hub dataset, e.g. to collect runs from several
machines in one place:

```bash
kernels benchmark kernels-community/activation@v1 --push-to-hub my-org/kernel-benchmarks
```

Runs saved with `--output` can be pushed later with `benchmark-push`. Runs of a
local checkout are recorded with its path, use `--record-as` to record them as
runs of the kernel on the Hub instead:

```bash
kernels benchmark-push my-org/kernel-benchmarks results/*.jsonl --record-as kernels-community/activation@v1
```

The dataset is created as a private dataset if it does not exist, pass
`--public` to create a public one. Pushing requires a token with write access,
see `hf auth login`.

Every run is stored as a separate file, so runs pushed at the same time from
different machines do not conflict:

```
data/<org>--<kernel>/<timestamp>-<device>-<run id>.parquet
```

`<device>` is the GPU the run used, or the backend (e.g. `cpu`) for runs without
a GPU. The files are written as Parquet with the same schema for every run, so runs
from different devices (e.g. with and without device timings) load as a single
table. In Parquet, `params` and `hardware` are stored as JSON strings. When the
dataset has no dataset card yet, one is added that configures `data/**/*.parquet`
as its data files, so that the dataset viewer and `datasets.load_dataset` show
all runs:

```python
import pandas as pd

df = pd.read_parquet("hf://datasets/my-org/kernel-benchmarks/data/")
```

## Writing Benchmark Scripts

Benchmark scripts must live under `benchmarks/` in the kernel repository and
Expand Down
1 change: 1 addition & 0 deletions flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,7 @@
pytest
pytest-benchmark
pytest-cov
pyarrow
pyyaml
sigstore
tabulate
Expand Down
1 change: 1 addition & 0 deletions kernels/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ dev = [
[project.optional-dependencies]
benchmark = [
"numpy>=2.0.2",
"pyarrow>=15",
"tabulate>=0.9.0",
"torch",
]
Expand Down
53 changes: 53 additions & 0 deletions kernels/src/kernels/_internals/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,9 +148,40 @@ def main():
default=None,
help="Compare against a previous run saved with `--output <file>.jsonl`",
)
benchmark_parser.add_argument(
"--benchmarks",
type=str,
default=None,
metavar="DIR",
help="Run the benchmark scripts in DIR instead of the ones in the kernel repo",
)
benchmark_parser.add_argument(
"--push-to-hub",
type=str,
default=None,
metavar="DATASET_REPO",
help="Push the results to a Hub dataset, created as a private dataset if it does not exist",
)
_add_push_arguments(benchmark_parser)
_add_compare_arguments(benchmark_parser)
benchmark_parser.set_defaults(func=run_benchmark)

benchmark_push_parser = subparsers.add_parser(
"benchmark-push",
help="Push benchmark runs saved with `kernels benchmark --output <file>.jsonl` to a Hub dataset",
)
benchmark_push_parser.add_argument("dataset_repo", type=str, help="Dataset repo ID (e.g., my-org/benchmarks)")
benchmark_push_parser.add_argument("files", type=str, nargs="+", help="Results of benchmark runs (.jsonl)")
benchmark_push_parser.add_argument(
"--record-as",
type=str,
default=None,
metavar="REPO_ID[@REVISION]",
help="Record the results as benchmarks of this kernel, e.g. for runs of a local checkout",
)
_add_push_arguments(benchmark_push_parser)
benchmark_push_parser.set_defaults(func=run_benchmark_push)

benchmark_compare_parser = subparsers.add_parser(
"benchmark-compare",
help="Compare two benchmark runs saved with `kernels benchmark --output <file>.jsonl`",
Expand Down Expand Up @@ -254,6 +285,25 @@ def _add_compare_arguments(parser):
)


def _add_push_arguments(parser):
parser.add_argument(
"--public",
action="store_true",
help="Create the dataset as a public dataset if it does not exist",
)


def run_benchmark_push(args):
from kernels._internals.cli import benchmark_hub

benchmark_hub.push_files(
args.dataset_repo,
args.files,
record_as=args.record_as,
private=not args.public,
)


def run_benchmark_compare(args):
from kernels._internals.cli import benchmark_compare

Expand All @@ -280,4 +330,7 @@ def run_benchmark(args):
output=args.output,
print_json=args.json,
show_stats=args.show_stats,
push_to_hub=args.push_to_hub,
public=args.public,
benchmarks=args.benchmarks,
)
40 changes: 35 additions & 5 deletions kernels/src/kernels/_internals/cli/benchmark.py
Original file line number Diff line number Diff line change
Expand Up @@ -643,15 +643,14 @@ def discover_benchmark_classes(script_path: Path, cwd: Path) -> list[type[Benchm

def discover_benchmark_scripts(
repo_id: str,
repo_path: Path,
benchmarks_dir: Path,
) -> list[Path]:
"""
Discover all benchmark scripts in the benchmarks directory.

Returns:
List of benchmark script paths
"""
benchmarks_dir = repo_path / "benchmarks"
if not benchmarks_dir.exists() or not benchmarks_dir.is_dir():
print(f"Error: No benchmarks directory found in '{repo_id}'", file=sys.stderr)
sys.exit(1)
Expand Down Expand Up @@ -719,6 +718,9 @@ def run_benchmark(
threshold: float = DEFAULT_THRESHOLD,
fail_on_regression: bool = False,
show_stats: bool = False,
push_to_hub: str | None = None,
public: bool = False,
benchmarks: str | None = None,
) -> BenchmarkResult:
if MISSING_DEPS:
print(
Expand All @@ -730,6 +732,16 @@ def run_benchmark(

# Read the baseline first, so that a bad path fails before benchmarking.
baseline_records = read_records(baseline) if baseline else None
if push_to_hub:
from kernels._internals.cli import benchmark_hub
from kernels._internals.cli.benchmark_results import _import_pyarrow

benchmark_hub.check_dataset_repo(push_to_hub)
try:
_import_pyarrow()
except ImportError as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)

# Suppress progress bars for cleaner output (files are often cached)
disable_progress_bars()
Expand Down Expand Up @@ -772,10 +784,14 @@ def run_benchmark(
revision = f"v{version}" if version is not None else branch
assert revision is not None # Guaranteed by parsing logic above

print(f"Downloading {repo_id}@{revision}...", file=sys.stderr)
if is_local:
if benchmarks is not None:
repo_path = Path(benchmarks).resolve().parent
benchmarks_dir = Path(benchmarks).resolve()
elif is_local:
repo_path = repo_id_path.resolve()
benchmarks_dir = repo_path / "benchmarks"
else:
print(f"Downloading {repo_id}@{revision}...", file=sys.stderr)
repo_path = Path(
str(
# Only the benchmark scripts are needed, the kernel itself is
Expand All @@ -788,8 +804,9 @@ def run_benchmark(
)
)
)
benchmarks_dir = repo_path / "benchmarks"

scripts = discover_benchmark_scripts(repo_id, repo_path)
scripts = discover_benchmark_scripts(repo_id, benchmarks_dir)

timing_results: dict[str, TimingResults] = {}
kernel_sha = ""
Expand Down Expand Up @@ -852,6 +869,19 @@ def run_benchmark(
for record in records:
print(json.dumps(record))

if push_to_hub:
try:
benchmark_hub.push_or_exit(push_to_hub, records, private=not public)
except SystemExit:
if not output:
fallback = f"kernels-benchmark-{records[0]['run_id'][:8]}.jsonl"
write_records(fallback, records)
print(
f"Results saved to: {fallback}, retry with: kernels benchmark-push {push_to_hub} {fallback}",
file=sys.stderr,
)
raise

if baseline_records is not None:
compare_report(
baseline_records,
Expand Down
Loading
Loading