From 9cee0dc49636a2e8273071b5088bbaa6760c6131 Mon Sep 17 00:00:00 2001 From: sayakpaul Date: Thu, 26 Nov 2026 09:48:59 +0530 Subject: [PATCH 1/3] kernels: support hf jobs while running benchmarks. --- docs/source/cli-benchmark.md | 47 +++++++++- .../src/kernels/_internals/cli/__init__.py | 12 +++ .../kernels/_internals/cli/benchmark_jobs.py | 72 +++++++++++++++ kernels/tests/test_cli_benchmark_jobs.py | 92 +++++++++++++++++++ 4 files changed, 222 insertions(+), 1 deletion(-) create mode 100644 kernels/src/kernels/_internals/cli/benchmark_jobs.py create mode 100644 kernels/tests/test_cli_benchmark_jobs.py diff --git a/docs/source/cli-benchmark.md b/docs/source/cli-benchmark.md index 769ccc57..f0327f6c 100644 --- a/docs/source/cli-benchmark.md +++ b/docs/source/cli-benchmark.md @@ -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]' @@ -118,6 +118,51 @@ 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 +``` + +Pass a space-separated list to `--flavor` to run the same workloads on several +machines. Include `--json` to make the workload records available in each job's +logs. + +```bash +kernels benchmark kernels-community/activation@v1 \ + --flavor l4x1 a10g-small h200 --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 `. To watch the benchmark as it runs, use +`hf jobs logs --follow `. + +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="" +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). diff --git a/kernels/src/kernels/_internals/cli/__init__.py b/kernels/src/kernels/_internals/cli/__init__.py index 9f92cc9d..849d3d80 100644 --- a/kernels/src/kernels/_internals/cli/__init__.py +++ b/kernels/src/kernels/_internals/cli/__init__.py @@ -129,6 +129,12 @@ 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", + nargs="+", + action="extend", + help="Submit one Hugging Face Job per hardware flavor (e.g. --flavor l4x1 h200)", + ) benchmark_parser.add_argument( "--output", type=str, @@ -275,6 +281,12 @@ 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 + from kernels._internals.cli import benchmark benchmark.run_benchmark( diff --git a/kernels/src/kernels/_internals/cli/benchmark_jobs.py b/kernels/src/kernels/_internals/cli/benchmark_jobs.py new file mode 100644 index 00000000..87e425fd --- /dev/null +++ b/kernels/src/kernels/_internals/cli/benchmark_jobs.py @@ -0,0 +1,72 @@ +"""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) + except (HfHubHTTPError, LocalTokenNotFoundError) as error: + raise SystemExit(f"Could not submit benchmark on {flavor}: {error}") from None + print(f"{flavor}: {job.url}", flush=True) diff --git a/kernels/tests/test_cli_benchmark_jobs.py b/kernels/tests/test_cli_benchmark_jobs.py new file mode 100644 index 00000000..2e115a5a --- /dev/null +++ b/kernels/tests/test_cli_benchmark_jobs.py @@ -0,0 +1,92 @@ +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, + *target, + "--flavor", + "l4x1", + "h200", + "l4x1", + "--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: + 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( + "args", + [ + ["."], + ["org/kernel"], + ["org/kernel@2"], + ["org/kernel@v2", "--output", "result.jsonl"], + ["org/kernel@v2", "--baseline", "base.jsonl"], + ["org/kernel@v2", "--iterations", "0"], + ], +) +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", "h200") + assert "https://example.org/jobs/first" in capsys.readouterr().out From fadd9b69a5bba1f1f543a90b2f36699137ae6b1e Mon Sep 17 00:00:00 2001 From: sayakpaul Date: Thu, 3 Dec 2026 13:13:10 +0530 Subject: [PATCH 2/3] add flavor single tag --- docs/source/cli-benchmark.md | 9 ++++----- kernels/src/kernels/_internals/cli/__init__.py | 5 ++--- kernels/tests/test_cli_benchmark_jobs.py | 6 ++++-- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/source/cli-benchmark.md b/docs/source/cli-benchmark.md index f0327f6c..8618427a 100644 --- a/docs/source/cli-benchmark.md +++ b/docs/source/cli-benchmark.md @@ -130,13 +130,12 @@ for hardware and billing details. kernels benchmark kernels-community/activation@v1 --flavor l4x1 ``` -Pass a space-separated list to `--flavor` to run the same workloads on several -machines. Include `--json` to make the workload records available in each job's -logs. +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 kernels-community/activation@v1 \ - --flavor l4x1 a10g-small h200 --warmup 20 --iterations 200 --json +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 diff --git a/kernels/src/kernels/_internals/cli/__init__.py b/kernels/src/kernels/_internals/cli/__init__.py index 849d3d80..dbddc482 100644 --- a/kernels/src/kernels/_internals/cli/__init__.py +++ b/kernels/src/kernels/_internals/cli/__init__.py @@ -131,9 +131,8 @@ def main(): benchmark_parser.add_argument("--version", type=int, help="Kernel version to benchmark") benchmark_parser.add_argument( "--flavor", - nargs="+", - action="extend", - help="Submit one Hugging Face Job per hardware flavor (e.g. --flavor l4x1 h200)", + action="append", + help="Submit a Hugging Face Job on this hardware flavor. Repeat --flavor to select multiple flavors.", ) benchmark_parser.add_argument( "--output", diff --git a/kernels/tests/test_cli_benchmark_jobs.py b/kernels/tests/test_cli_benchmark_jobs.py index 2e115a5a..c21a1b80 100644 --- a/kernels/tests/test_cli_benchmark_jobs.py +++ b/kernels/tests/test_cli_benchmark_jobs.py @@ -33,11 +33,13 @@ def jobs(monkeypatch): def test_submit_benchmark_jobs(monkeypatch, jobs, target, worker_args, capsys): run_cli( monkeypatch, - *target, "--flavor", "l4x1", + "--flavor", "h200", + "--flavor", "l4x1", + *target, "--iterations", "20", "--warmup", @@ -88,5 +90,5 @@ def test_submission_failure_preserves_earlier_job_url(monkeypatch, jobs, capsys) LocalTokenNotFoundError("login required"), ] with pytest.raises(SystemExit, match="h200: login required"): - run_cli(monkeypatch, "org/kernel@main", "--flavor", "l4x1", "h200") + run_cli(monkeypatch, "org/kernel@main", "--flavor", "l4x1", "--flavor", "h200") assert "https://example.org/jobs/first" in capsys.readouterr().out From ccfd9f7bd79ca46385894db999df80142915c37a Mon Sep 17 00:00:00 2001 From: sayakpaul Date: Thu, 3 Dec 2026 13:29:09 +0530 Subject: [PATCH 3/3] introduce timeout. --- docs/source/cli-benchmark.md | 10 ++++++--- .../src/kernels/_internals/cli/__init__.py | 21 +++++++++++++++++++ .../kernels/_internals/cli/benchmark_jobs.py | 4 +++- kernels/tests/test_cli_benchmark_jobs.py | 17 +++++++++++++++ 4 files changed, 48 insertions(+), 4 deletions(-) diff --git a/docs/source/cli-benchmark.md b/docs/source/cli-benchmark.md index 8618427a..394fde4d 100644 --- a/docs/source/cli-benchmark.md +++ b/docs/source/cli-benchmark.md @@ -127,11 +127,15 @@ 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 +kernels benchmark kernels-community/activation@v1 --flavor l4x1 --timeout 45m ``` -Repeat `--flavor` to run the same workloads on several hardware flavors. -Include `--json` to make the workload records available in each job's logs. +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 \ diff --git a/kernels/src/kernels/_internals/cli/__init__.py b/kernels/src/kernels/_internals/cli/__init__.py index d17adc00..815c24b2 100644 --- a/kernels/src/kernels/_internals/cli/__init__.py +++ b/kernels/src/kernels/_internals/cli/__init__.py @@ -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 @@ -129,6 +131,12 @@ def main(): 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.", + ) benchmark_parser.add_argument( "--output", type=str, @@ -188,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" @@ -277,6 +295,9 @@ def run_benchmark(args): 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( diff --git a/kernels/src/kernels/_internals/cli/benchmark_jobs.py b/kernels/src/kernels/_internals/cli/benchmark_jobs.py index 87e425fd..befd4ef9 100644 --- a/kernels/src/kernels/_internals/cli/benchmark_jobs.py +++ b/kernels/src/kernels/_internals/cli/benchmark_jobs.py @@ -66,7 +66,9 @@ def submit_benchmark_jobs(args: argparse.Namespace) -> None: 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) + 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) diff --git a/kernels/tests/test_cli_benchmark_jobs.py b/kernels/tests/test_cli_benchmark_jobs.py index c21a1b80..6829bdce 100644 --- a/kernels/tests/test_cli_benchmark_jobs.py +++ b/kernels/tests/test_cli_benchmark_jobs.py @@ -50,6 +50,7 @@ def test_submit_benchmark_jobs(monkeypatch, jobs, target, worker_args, capsys): 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, @@ -67,6 +68,19 @@ def test_submit_benchmark_jobs(monkeypatch, jobs, target, worker_args, capsys): ] +@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", [ @@ -76,6 +90,9 @@ def test_submit_benchmark_jobs(monkeypatch, jobs, target, worker_args, capsys): ["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):