Skip to content
Merged
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
45 changes: 45 additions & 0 deletions .github/workflows/gpu.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ jobs:

steps:
- uses: actions/checkout@v4
with:
fetch-depth: 2

- name: Install LLVM ${{ env.LLVM_VERSION }} and MLIR
run: |
Expand Down Expand Up @@ -68,6 +70,49 @@ jobs:
fi
uv run pytest -v -m gpu

- name: Compare against the base branch on Vast.ai
if: success() && github.event_name == 'pull_request'
timeout-minutes: 25
env:
VASTAI_API_KEY: ${{ secrets.VASTAI_API_KEY }}
BASE_REF: ${{ github.base_ref }}
COMMENT_PATH: ${{ runner.temp }}/bench-comment.md
run: |
set -euo pipefail
# HEAD is GitHub's merge of this pull request. HEAD^1 is the base commit
# that merge used, which fetch-depth 2 makes available. A depth-1 checkout
# records the parent SHAs and still cannot resolve them.
git branch --force "$BASE_REF" HEAD^1
uv run python -m bench compare "$BASE_REF" HEAD --comment "$COMMENT_PATH"

- name: Post the bench comparison
if: always() && github.event_name == 'pull_request'
env:
GH_TOKEN: ${{ github.token }}
PR_NUMBER: ${{ github.event.pull_request.number }}
COMMENT_PATH: ${{ runner.temp }}/bench-comment.md
run: |
set -euo pipefail
if [ ! -s "$COMMENT_PATH" ]; then
echo "no bench comment to post"
exit 0
fi
export MARKER
MARKER="$(head -n 1 "$COMMENT_PATH")"
id="$(gh api --paginate "repos/${GITHUB_REPOSITORY}/issues/${PR_NUMBER}/comments" \
--jq '.[] | select(.user.login == "github-actions[bot]" and (.body | startswith(env.MARKER))) | .id' \
| tail -n 1)"
# -F reads the file. -f posts the path string as the comment body.
if [ -n "$id" ]; then
gh api --method PATCH \
"repos/${GITHUB_REPOSITORY}/issues/comments/${id}" \
-F body=@"$COMMENT_PATH"
else
gh api --method POST \
"repos/${GITHUB_REPOSITORY}/issues/${PR_NUMBER}/comments" \
-F body=@"$COMMENT_PATH"
fi

- name: Remove GPU test trigger label
if: always() && github.event_name == 'pull_request'
env:
Expand Down
13 changes: 13 additions & 0 deletions bench/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,19 @@ def resolve(repo: Path, name: str) -> Ref:
return Ref(name=name, sha=result.stdout.strip())


def parents(repo: Path, ref: Ref) -> tuple[str, ...]:
"""Parents of `ref` in order. A root commit is an empty tuple.

`--verify` is not used. `rev-parse --verify <sha>^@` exits 128 for a parent list.
"""
result = _git(repo, "rev-parse", f"{ref.sha}^@")
if result.returncode != 0:
detail = result.stderr.strip() or result.stdout.strip()
msg = f"cannot read parents of {ref.name} at {ref.short}: {detail}"
raise BuildError(msg)
return tuple(result.stdout.split())


def toolchain_of(build_dir: Path) -> Toolchain:
"""The MLIR and LLVM a fresh build needs, from the environment or a configured build.

Expand Down
81 changes: 63 additions & 18 deletions bench/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,17 @@
import os
import subprocess
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING

from bench import acceptance, build, compare, gap
from bench import acceptance, build, comment, compare, gap
from bench.report import Report
from benchmarks import manifest
from gpu_test import bench_stats, infrastructure

if TYPE_CHECKING:
from collections.abc import Sequence
from collections.abc import Callable, Sequence

logger = logging.getLogger("bench")
REPO_ROOT = manifest.CASE_ROOT.parent
Expand Down Expand Up @@ -107,15 +109,14 @@ def run(args: argparse.Namespace) -> int:


def compile_both(
cases: Sequence[manifest.Case], args: argparse.Namespace
) -> tuple[build.Ref, build.Ref, dict[str, compare.BaseSide], list[gap.Item]]:
"""Build both refs and compile every case with each binary inside that ref's worktree.

A worktree is torn down as soon as it has produced its PTX, so the two compilers never share a
build directory and nothing depends on where the temporary checkouts live.
cases: Sequence[manifest.Case],
base: build.Ref,
head: build.Ref,
args: argparse.Namespace,
) -> tuple[dict[str, compare.BaseSide], list[gap.Item]]:
"""A worktree is torn down as soon as it has produced its PTX, so the two compilers never
share a build directory and nothing depends on where the temporary checkouts live.
"""
base = build.resolve(REPO_ROOT, args.base)
head = build.resolve(REPO_ROOT, args.head)
logger.info("base %s at %s, head %s at %s", base.name, base.short, head.name, head.short)
toolchain = build.toolchain_of(manifest.find_build(REPO_ROOT))
logger.info("compiling %d cases with both revisions at %s", len(cases), args.arch)
Expand All @@ -129,16 +130,24 @@ def compile_both(
error = item.error if isinstance(item, gap.Broken) else base_error
if error:
logger.error("%s: %s", item.case.id, error)
return base, head, bases, items
return bases, items


def run_compare(args: argparse.Namespace) -> int:
cases = select_cases(manifest.load(), args.case)
key = api_key()
base, head, bases, items = compile_both(cases, args)
if all(isinstance(item, gap.Broken) for item in items):
return EXIT_INCOMPLETE
@dataclass(frozen=True, slots=True)
class UnbuiltHead:
pass


def compare_refs(
cases: Sequence[manifest.Case],
base: build.Ref,
head: build.Ref,
key: str,
args: argparse.Namespace,
) -> compare.Report | UnbuiltHead:
bases, items = compile_both(cases, base, head, args)
if all(isinstance(item, gap.Broken) for item in items):
return UnbuiltHead()
commits = {"base_commit": base.sha, "head_commit": head.sha}
logger.info("building the CUDA baselines and timing %d cases on one rental", len(items))
with infrastructure.VastSession(key, arch=args.arch) as session:
Expand All @@ -148,8 +157,27 @@ def run_compare(args: argparse.Namespace) -> int:
harness.request({"op": "ping"}), base.sha, head.sha
)
rows = compare.rows_of(readied, bases, harness, commits)
return compare.Report(arch=args.arch, environment=environment, rows=tuple(rows))


report = compare.Report(arch=args.arch, environment=environment, rows=tuple(rows))
def run_compare(args: argparse.Namespace) -> int:
cases = select_cases(manifest.load(), args.case)
key = api_key()
base = build.resolve(REPO_ROOT, args.base)
head = build.resolve(REPO_ROOT, args.head)
revisions = comment.Revisions.of(base, head, build.parents(REPO_ROOT, head))
publish = comment_writer(args.comment)
publish(comment.Unfinished(revisions))
try:
outcome = compare_refs(cases, base, head, key, args)
except BaseException as exc:
publish(comment.Failed.from_error(revisions, exc))
raise
if isinstance(outcome, UnbuiltHead):
publish(comment.Failed(revisions, "no case compiled with the head revision"))
return EXIT_INCOMPLETE
report = outcome
publish(comment.Measured(revisions, report))
for line in report.lines():
print(line) # noqa: T201 - the command's own output
if args.json:
Expand All @@ -159,6 +187,18 @@ def run_compare(args: argparse.Namespace) -> int:
return 0 if not report.failures else EXIT_INCOMPLETE


def comment_writer(path: Path | None) -> Callable[[comment.State], None]:
def write(state: comment.State) -> None:
if path is None:
return
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_name(f".{path.name}.tmp")
temporary.write_text(comment.render(state), encoding="utf-8", newline="\n")
temporary.replace(path)

return write


def run_acceptance(args: argparse.Namespace) -> int:
cases = manifest.load()
key = api_key()
Expand Down Expand Up @@ -206,6 +246,11 @@ def build_parser() -> argparse.ArgumentParser:
default=BUILD_JOBS,
help="parallel compile jobs for each of the two fresh builds",
)
compare_command.add_argument(
"--comment",
type=Path,
help="write the review comment to this path as the run goes, without posting it",
)
acceptance_command = subcommands.add_parser(
"acceptance",
parents=[shared],
Expand Down
162 changes: 162 additions & 0 deletions bench/comment.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
from __future__ import annotations

from dataclasses import dataclass
from typing import TYPE_CHECKING

if TYPE_CHECKING:
from collections.abc import Sequence

from bench import build, compare

MARKER = "<!-- warpforth-bench-compare -->"
_MERGE_PARENTS = 2
_MIN_FENCE = 3
_RATIO_DIGITS = 3
_GAP_DIGITS = 2
_TIME_DIGITS = 1
_TEXT_COLUMNS = 2
_NUMERIC_COLUMNS = 5
_HEADERS = ("case", "verdict", "ratio", "mad", "base", "head", "gap")


@dataclass(frozen=True, slots=True)
class Revisions:
base: build.Ref
head: build.Ref
pull_head: str | None

@classmethod
def of(cls, base: build.Ref, head: build.Ref, head_parents: Sequence[str]) -> Revisions:
pull_head = None
if len(head_parents) == _MERGE_PARENTS and head_parents[0] == base.sha:
pull_head = head_parents[1]
return cls(base, head, pull_head)


@dataclass(frozen=True, slots=True)
class Unfinished:
revisions: Revisions


@dataclass(frozen=True, slots=True)
class Failed:
revisions: Revisions
reason: str

@classmethod
def from_error(cls, revisions: Revisions, error: BaseException) -> Failed:
if isinstance(error, KeyboardInterrupt):
return cls(revisions, "interrupted")
return cls(revisions, f"{type(error).__name__}: {error}")


@dataclass(frozen=True, slots=True)
class Measured:
revisions: Revisions
report: compare.Report


State = Unfinished | Failed | Measured


def render(state: State) -> str:
lines = [MARKER, _headline(state), ""]
result = _result(state)
if result is not None:
lines.extend([result, ""])
lines.append(_details(state))
return "\n".join(lines) + "\n"


def _headline(state: State) -> str:
return f"### Bench compare against `{state.revisions.base.name}`: {_status(state)}"


def _status(state: State) -> str:
if isinstance(state, Measured):
return state.report.summary
if isinstance(state, Failed):
return "no result"
return "did not finish"


def _result(state: State) -> str | None:
if isinstance(state, Measured):
return _table(state.report)
if isinstance(state, Failed):
return _fence(state.reason)
return None


def _table(report: compare.Report) -> str:
notes = any(row.outcome.note for row in report.rows)
headers = [*_HEADERS, "note"] if notes else list(_HEADERS)
rows = [_markdown_row(headers), _separator(len(headers))]
for row in report.rows:
cells = _cells(row)
if notes:
cells.append(_cell(row.outcome.note))
rows.append(_markdown_row(cells))
return "\n".join(rows)


def _cells(row: compare.Row) -> list[str]:
outcome = row.outcome
stats = outcome.stats
verdict = outcome.verdict.value if outcome.verdict else "-"
ratio = f"{stats.ratio_median:.{_RATIO_DIGITS}f}" if stats else "-"
mad = f"{stats.ratio_mad:.{_RATIO_DIGITS}f}" if stats else "-"
base = f"{stats.base_median_us:.{_TIME_DIGITS}f} us" if stats else "-"
head = f"{stats.head_median_us:.{_TIME_DIGITS}f} us" if stats else "-"
gap = f"{outcome.head_gap:.{_GAP_DIGITS}f}x" if outcome.head_gap is not None else "-"
return [_cell(value) for value in (row.case.id, verdict, ratio, mad, base, head, gap)]


def _markdown_row(cells: Sequence[str]) -> str:
return "| " + " | ".join(cells) + " |"


def _separator(columns: int) -> str:
cells = []
for index in range(columns):
numeric = _TEXT_COLUMNS <= index < _TEXT_COLUMNS + _NUMERIC_COLUMNS
cells.append("---:" if numeric else "---")
return _markdown_row(cells)


def _cell(value: str) -> str:
return " ".join(value.replace("|", "\\|").split())


def _details(state: State) -> str:
revisions = state.revisions
bullets = [f"Base: `{revisions.base.sha}`", f"Head: `{revisions.head.sha}`"]
if isinstance(state, Measured):
bullets.append(_rental(state.report))
return "\n".join(f"- {bullet}" for bullet in bullets)


def _rental(report: compare.Report) -> str:
environment = report.environment
return (
f"Rental: `{environment.gpu_uuid}`, driver {environment.driver_version}, "
f"SM clock {environment.sm_clock_mhz} MHz, "
f"memory clock {environment.memory_clock_mhz} MHz, `{report.arch}`"
)


def _fence(text: str) -> str:
ticks = "`" * max(_backtick_run(text) + 1, _MIN_FENCE)
return f"{ticks}\n{text}\n{ticks}"


def _backtick_run(text: str) -> int:
longest = 0
run = 0
for char in text:
if char == "`":
run += 1
longest = max(longest, run)
else:
run = 0
return longest
5 changes: 3 additions & 2 deletions bench/compare.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,13 +136,14 @@ def lines(self) -> list[str]:
header,
*(_row_line(row) for row in self.rows),
"",
self._sum_line(),
self.summary,
]

def _environment_line(self) -> str:
return " ".join(f"{name}={getattr(self.environment, name)}" for name in ENVIRONMENT_FIELDS)

def _sum_line(self) -> str:
@property
def summary(self) -> str:
total = len(self.rows)
if self.regressions:
return f"{len(self.regressions)} of {total} cases slower: {', '.join(self.regressions)}"
Expand Down
Loading
Loading