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
50 changes: 49 additions & 1 deletion docs/source/cli-benchmark.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ The command:

## Installation

`kernels benchmark` requires extra dependencies:
Install the benchmark dependencies to run workloads locally.

```bash
uv pip install 'kernels[benchmark]' # or pip install 'kernels[benchmark]'
Expand Down Expand Up @@ -118,6 +118,54 @@ Benchmark a local kernel checkout (must contain `benchmarks/`):
kernels benchmark ./my_kernel
```

## Running on Hugging Face Jobs

Use `--flavor` to submit a public Hub kernel to Hugging Face Jobs. Log in with
`hf auth login` using a token with permission to run Jobs. List available
hardware with `hf jobs hardware`. Each selected flavor starts a billable job.
See the [HF Jobs guide](https://huggingface.co/docs/huggingface_hub/guides/jobs)
for hardware and billing details.

```bash
kernels benchmark kernels-community/activation@v1 --flavor l4x1 --timeout 45m
```

Use `--timeout` to set the maximum runtime of each job. A plain integer is in
seconds, and a suffix such as `m` or `h` specifies minutes or hours. Omit the
flag to use the HF Jobs default.

Repeat `--flavor` to run the same workloads on several hardware flavors. Include
`--json` to make the workload records available in each job's logs.

```bash
kernels benchmark --flavor l4x1 --flavor a10g-small --flavor h200 \
kernels-community/activation@v1 --warmup 20 --iterations 200 --json
```

The command prints a URL for each job and exits after submission. The job
installs the benchmark dependencies on the worker. Released versions use the
same `kernels` version on the worker and the submitting machine. Development
versions install the runner from the upstream `main` branch.

### Fetching results

Open a job URL to see its results table, or use the ID at the end of the URL
with `hf jobs logs <job_id>`. To watch the benchmark as it runs, use
`hf jobs logs --follow <job_id>`.

For a job submitted with `--json`, wait for it to finish successfully and use
`jq` to extract the workload records from the logs. For example, to save the L4
run on your machine:

```bash
job_id="<L4 job ID>"
hf jobs wait "$job_id" && hf jobs logs "$job_id" \
| jq -Rce 'fromjson? | objects | select(has("run_id") and has("workload"))' > l4x1.jsonl
```

Use each flavor's job ID and a separate filename when fetching multiple runs.
These files have the same format as a local `kernels benchmark --output` file.

## Output

- By default, a table is printed (timings in ms).
Expand Down
32 changes: 32 additions & 0 deletions kernels/src/kernels/_internals/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
from pathlib import Path
from typing import Literal

from huggingface_hub.utils._parsing import parse_duration

from kernels._internals.cli.cache import print_cached_kernels
from kernels._internals.cli.describe_api import print_kernel_api
from kernels._internals.cli.download import download_kernels
Expand Down Expand Up @@ -124,6 +126,17 @@ def main():
)
benchmark_parser.add_argument("--branch", type=str, help="Kernel branch to benchmark")
benchmark_parser.add_argument("--version", type=int, help="Kernel version to benchmark")
benchmark_parser.add_argument(
"--flavor",
action="append",
help="Submit a Hugging Face Job on this hardware flavor. Repeat --flavor to select multiple flavors.",
)
benchmark_parser.add_argument(
"--timeout",
type=_job_timeout,
metavar="DURATION",
help="Maximum runtime for each Hugging Face Job, e.g. 300 (seconds), 5m, or 1h. Requires --flavor.",
)
Comment thread
sayakpaul marked this conversation as resolved.
Resolved
benchmark_parser.add_argument(
"--output",
type=str,
Expand Down Expand Up @@ -183,6 +196,16 @@ def main():
args.func(args)


def _job_timeout(value: str) -> int:
try:
seconds = parse_duration(value)
except ValueError:
raise argparse.ArgumentTypeError("use a duration such as 300, 5m, or 1h") from None
if seconds <= 0:
raise argparse.ArgumentTypeError("the job timeout must be positive")
return seconds


def _variant_version(value: str) -> int | Literal["latest"]:
if value == "latest":
return "latest"
Expand Down Expand Up @@ -266,6 +289,15 @@ def run_benchmark_compare(args):


def run_benchmark(args):
if args.flavor:
from kernels._internals.cli.benchmark_jobs import submit_benchmark_jobs

submit_benchmark_jobs(args)
return

if args.timeout is not None:
raise SystemExit("--timeout requires --flavor to submit a Hugging Face Job.")

from kernels._internals.cli import benchmark

benchmark.run_benchmark(
Expand Down
74 changes: 74 additions & 0 deletions kernels/src/kernels/_internals/cli/benchmark_jobs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
"""Submit the benchmark CLI to Hugging Face Jobs."""

import argparse
import shlex
from pathlib import Path

from huggingface_hub.errors import HfHubHTTPError, HFValidationError, LocalTokenNotFoundError
from huggingface_hub.utils import validate_repo_id
from packaging.version import Version

from kernels import __version__
from kernels._internals.cli.benchmark_compare import DEFAULT_THRESHOLD
from kernels._internals.hf_hub import _get_hf_api


def submit_benchmark_jobs(args: argparse.Namespace) -> None:
if any(not flavor.strip() for flavor in args.flavor):
raise SystemExit("--flavor requires a hardware flavor from `hf jobs hardware`.")
if Path(args.repo_id).exists() or args.repo_id.startswith(("./", "../", "/", "~")):
raise SystemExit("--flavor requires a Hub kernel repository ID. Omit --flavor to benchmark a local checkout.")
if args.output is not None:
raise SystemExit("--output writes a local file. Use --json to include JSON Lines in the job logs.")
if args.baseline is not None or args.fail_on_regression or args.threshold != DEFAULT_THRESHOLD:
raise SystemExit("Baseline comparisons require local files and cannot be used with --flavor.")
if args.iterations <= 0 or args.warmup < 0:
raise SystemExit("Benchmarks require a positive --iterations count and a non-negative --warmup count.")

repo_id = args.repo_id
revision_args = []
if args.version is not None:
revision_args = ["--version", str(args.version)]
elif args.branch:
revision_args = [f"--branch={args.branch}"]
else:
repo_id, _, revision = repo_id.partition("@")
if not revision or revision.isdigit():
raise SystemExit("Specify a branch or version with --branch, --version, @branch, or @vN.")
try:
validate_repo_id(repo_id)
except HFValidationError as error:
raise SystemExit(str(error)) from None

# Development checkouts can contain benchmark features that have yet to reach PyPI.
requirement = (
"kernels[benchmark] @ git+https://github.com/huggingface/kernels.git@main#subdirectory=kernels"
if Version(__version__).is_devrelease
else f"kernels[benchmark]=={__version__}"
)
command = [
"sh",
"-c",
f'uv pip install --system --torch-backend=auto {shlex.quote(requirement)} && exec kernels benchmark "$@"',
"benchmark",
args.repo_id,
*revision_args,
"--iterations",
str(args.iterations),
"--warmup",
str(args.warmup),
]
if args.json:
command.append("--json")
if args.show_stats:
command.append("--show-stats")

api = _get_hf_api()
for flavor in dict.fromkeys(args.flavor):
try:
job = api.run_job(
image="ghcr.io/astral-sh/uv:python3.12-bookworm", command=command, flavor=flavor, timeout=args.timeout
)
except (HfHubHTTPError, LocalTokenNotFoundError) as error:
raise SystemExit(f"Could not submit benchmark on {flavor}: {error}") from None
print(f"{flavor}: {job.url}", flush=True)
111 changes: 111 additions & 0 deletions kernels/tests/test_cli_benchmark_jobs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import sys
from types import SimpleNamespace
from unittest.mock import Mock

import pytest
from huggingface_hub.errors import LocalTokenNotFoundError

from kernels._internals.cli import benchmark_jobs, main


def run_cli(monkeypatch, *args):
monkeypatch.setattr(sys, "argv", ["kernels", "benchmark", *args])
main()


@pytest.fixture
def jobs(monkeypatch):
api = Mock()
api.run_job.side_effect = lambda *, flavor, **kwargs: SimpleNamespace(url=f"https://example.org/jobs/{flavor}")
monkeypatch.setattr(benchmark_jobs, "_get_hf_api", lambda: api)
return api.run_job


@pytest.mark.parametrize(
("target", "worker_args"),
[
(["org/kernel@v2"], ["org/kernel@v2"]),
(["org/kernel", "--version", "0"], ["org/kernel", "--version", "0"]),
(["org/kernel@feature/test"], ["org/kernel@feature/test"]),
(["org/kernel", "--branch", "feature/test"], ["org/kernel", "--branch=feature/test"]),
],
)
def test_submit_benchmark_jobs(monkeypatch, jobs, target, worker_args, capsys):
run_cli(
monkeypatch,
"--flavor",
"l4x1",
"--flavor",
"h200",
"--flavor",
"l4x1",
*target,
"--iterations",
"20",
"--warmup",
"0",
"--json",
"--show-stats",
)

assert [call.kwargs["flavor"] for call in jobs.call_args_list] == ["l4x1", "h200"]
for call in jobs.call_args_list:
assert call.kwargs["timeout"] is None
command = call.kwargs["command"]
assert command[command.index(target[0]) :] == [
*worker_args,
"--iterations",
"20",
"--warmup",
"0",
"--json",
"--show-stats",
]
assert "secrets" not in call.kwargs
assert capsys.readouterr().out.splitlines() == [
"l4x1: https://example.org/jobs/l4x1",
"h200: https://example.org/jobs/h200",
]


@pytest.mark.parametrize(("duration", "seconds"), [("300", 300), ("45m", 2700), ("2h", 7200)])
def test_timeout_applies_to_each_job(monkeypatch, jobs, duration, seconds):
run_cli(monkeypatch, "org/kernel@main", "--flavor", "l4x1", "--flavor", "h200", "--timeout", duration)
assert [call.kwargs["timeout"] for call in jobs.call_args_list] == [seconds, seconds]
for call in jobs.call_args_list:
assert "--timeout" not in call.kwargs["command"]


def test_timeout_requires_remote_job(monkeypatch):
with pytest.raises(SystemExit, match="--timeout requires --flavor"):
run_cli(monkeypatch, "org/kernel@main", "--timeout", "5m")


@pytest.mark.parametrize(
"args",
[
["."],
["org/kernel"],
["org/kernel@2"],
["org/kernel@v2", "--output", "result.jsonl"],
["org/kernel@v2", "--baseline", "base.jsonl"],
["org/kernel@v2", "--iterations", "0"],
["org/kernel@v2", "--timeout", "0"],
["org/kernel@v2", "--timeout", "-1"],
["org/kernel@v2", "--timeout", "soon"],
],
)
def test_invalid_submission_creates_no_job(monkeypatch, jobs, args):
with pytest.raises(SystemExit):
run_cli(monkeypatch, *args, "--flavor", "h200")
jobs.assert_not_called()


def test_submission_failure_preserves_earlier_job_url(monkeypatch, jobs, capsys):
jobs.side_effect = [
SimpleNamespace(url="https://example.org/jobs/first"),
LocalTokenNotFoundError("login required"),
]
with pytest.raises(SystemExit, match="h200: login required"):
run_cli(monkeypatch, "org/kernel@main", "--flavor", "l4x1", "--flavor", "h200")
assert "https://example.org/jobs/first" in capsys.readouterr().out
Loading