Repository navigation
kernels: support hf jobs while running benchmarks. #1049
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
sayakpaul
wants to merge
4
commits into
main
Choose a base branch
from
kernels-benchmark-hf-jobs
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+266
−1
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.