Datasets:
File size: 6,599 Bytes
e58c676 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 | """Benchmark gains documented in PR descriptions: fetch bodies (gh) and extract measurements (LLM, HF Inference)."""
import json
import re
import statistics
import subprocess
import sys
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from huggingface_hub import InferenceClient
CACHE = Path(__file__).parent / ".context/prs"
MODEL = "Qwen/Qwen3-235B-A22B-Instruct-2507"
FALLBACK = "openai/gpt-oss-120b:cerebras" # ~40x faster; for dense tables that exceed the 120s gateway timeout
MAX_BODY = 24_000 # stored in the dataset
MAX_SOURCE, CHUNK = 80_000, 4_000 # read for extraction, per LLM call
# cheap prefilter: skip the LLM when the body has no perf numbers at all
HAS_NUMBERS = re.compile(r"\d+(?:\.\d+)?\s?(?:[x×](?![\w\d])|%|us\b|µs|ms\b|tflops|gb/s|tok/s|tokens/s)", re.I)
PROMPT = """Extract the performance measurements from this GitHub pull request description of a GPU kernel change.
Only extract before-vs-after comparisons where the baseline is the code/config BEFORE this PR (main, default config, \
previous kernel, "before") and the optimized side is THIS PR ("after", "tuned", "PR"). Skip comparisons against other \
libraries or alternatives, accuracy/eval scores, and anything not explicitly in the text. Never invent or compute numbers.
Return JSON: {{"measurements": [{{
"scope": "kernel" | "e2e", // kernel micro-benchmark vs end-to-end serving/model benchmark
"hardware": str | null, // e.g. "H100", "B200", "MI300X"
"model": str | null, // e.g. "DeepSeek-V3"
"shape": str | null, // other shape params, e.g. "N=7168,K=2048" or "hidden=4096"
"batch_size": int | null, // batch size / num tokens / M, if the row has one
"metric": str, // e.g. "latency", "throughput", "TFLOPS"
"unit": str | null, // e.g. "us", "tok/s"
"higher_is_better": bool, // false for latency/time, true for throughput/TFLOPS/bandwidth
"baseline": number | null,
"optimized": number | null,
"stated_speedup": number | null // ONLY if the text states a speedup ratio without raw values (e.g. "1.3x" -> 1.3, "+20%" -> 1.2)
}}]}}
Return {{"measurements": []}} if there are none. One entry per table row / reported number.
PR title: {title}
PR description:
{body}"""
def _key(repo: str, n: int) -> str:
return f"{repo.replace('/', '__')}-{n}"
def pr_body(repo: str, n: int) -> str | None:
"""PR description, or None if the fetch failed (so callers don't cache a fake empty body)."""
f = CACHE / f"{_key(repo, n)}.md"
if not f.exists():
r = subprocess.run(["gh", "api", f"repos/{repo}/pulls/{n}", "--jq", '.body // ""'], capture_output=True, text=True)
if r.returncode and "404" not in r.stderr: # not cached: transient errors (rate limit) retry next build
print(f" gh {repo}#{n}: {r.stderr.strip()[:100]}", file=sys.stderr)
return None
f.write_text(r.stdout if not r.returncode else "") # 404 = "(#n)" was an issue, not a PR
return f.read_text()
def speedup(m: dict) -> float | None:
"""Normalized so > 1 means this PR is better."""
b, o = m.get("baseline"), m.get("optimized")
if isinstance(b, (int, float)) and isinstance(o, (int, float)) and b > 0 and o > 0:
return round(o / b if m.get("higher_is_better") else b / o, 4)
s = m.get("stated_speedup")
return float(s) if isinstance(s, (int, float)) and s > 0 else None
def chunks(body: str) -> list[str]:
"""Split on blank lines into <= CHUNK pieces: one call per long benchmark table section stays under the
gateway timeout. An oversized paragraph (a giant table) is split by lines, repeating its 2 header lines."""
out = [""]
for para in body[:MAX_SOURCE].split("\n\n"):
lines = para.splitlines()
pieces = [para] if len(para) <= CHUNK else [
"\n".join(lines[:2] + lines[i : i + 60]) for i in range(2, len(lines), 60)]
for p in pieces:
if out[-1] and len(out[-1]) + len(p) > CHUNK:
out.append("")
out[-1] += p + "\n\n"
return out
def _llm(client: InferenceClient, content: str) -> list[dict]:
for attempt, model in enumerate([MODEL, FALLBACK, FALLBACK]): # gateway 5xx/timeouts are common
try:
r = client.chat_completion(model=model, max_tokens=16000, temperature=0, response_format={"type": "json_object"},
messages=[{"role": "user", "content": content}])
return json.loads(r.choices[0].message.content)["measurements"]
except Exception:
if attempt == 2:
raise
def extract(repo: str, n: int, title: str, client: InferenceClient) -> list[dict]:
f = CACHE / f"{_key(repo, n)}.gains.json"
if f.exists():
return json.loads(f.read_text())
body = pr_body(repo, n)
if body is None:
return []
ms = []
if HAS_NUMBERS.search(body):
parts = chunks(body)
try:
for i, part in enumerate(parts):
ctx = "" if i == 0 else f"(Part {i + 1}/{len(parts)}. For context only, the description starts: " \
f"{body[:1200]!r}. Extract ONLY from the part below.)\n\n"
ms += _llm(client, PROMPT.format(title=title, body=ctx + part))
except Exception as e: # not cached: retry on the next build
print(f" llm {repo}#{n}: {type(e).__name__} {str(e)[:100]}", file=sys.stderr)
return []
ms = [m | {"speedup": speedup(m)} for m in ms if isinstance(m, dict)]
ms = [m for m in ms if m["speedup"] and 0.01 < m["speedup"] < 1000] # drop unparseable / absurd rows
f.write_text(json.dumps(ms))
return ms
def fetch_all(prs: dict[tuple[str, int], str], workers: int = 24) -> dict[tuple[str, int], tuple[str, list[dict]]]:
"""{(gh_repo, pr): title} -> {(gh_repo, pr): (body, measurements)}"""
CACHE.mkdir(parents=True, exist_ok=True)
client = InferenceClient()
keys = sorted(prs)
with ThreadPoolExecutor(workers) as ex:
bodies = list(ex.map(lambda k: pr_body(*k), keys))
gains = list(ex.map(lambda k: extract(*k, prs[k], client), keys))
print(f" PRs: {len(keys)}, with gains: {sum(bool(g) for g in gains)}", file=sys.stderr)
return {k: (b or "", g) for k, b, g in zip(keys, bodies, gains)}
def summarize(ms: list[dict], scope: str) -> float | None:
s = [m["speedup"] for m in ms if m.get("scope") == scope]
return round(statistics.median(s), 4) if s else None
|