Datasets:
Upload folder using huggingface_hub
Browse files- code/build.py +443 -0
- code/gains.py +137 -0
- code/pyproject.toml +8 -0
- code/reward.py +63 -0
- code/test_build.py +61 -0
- code/uv.lock +0 -0
code/build.py
ADDED
|
@@ -0,0 +1,443 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build a kernel-optimization RL dataset from vLLM / SGLang / FlashInfer source and git history.
|
| 2 |
+
|
| 3 |
+
Subsets:
|
| 4 |
+
tuned_configs - (Triton kernel source, model shape, GPU, batch size) -> autotuned launch config.
|
| 5 |
+
kernel_commits - before/after kernel code from performance commits, tagged with model + hardware.
|
| 6 |
+
|
| 7 |
+
Usage: uv run build.py [--push REPO_ID] [--from-disk]
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import ast
|
| 11 |
+
import difflib
|
| 12 |
+
import functools
|
| 13 |
+
import hashlib
|
| 14 |
+
import json
|
| 15 |
+
import re
|
| 16 |
+
import statistics
|
| 17 |
+
import subprocess
|
| 18 |
+
import sys
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
from datasets import Dataset, DatasetDict, load_from_disk
|
| 22 |
+
from huggingface_hub import HfApi, hf_hub_download
|
| 23 |
+
|
| 24 |
+
import gains
|
| 25 |
+
|
| 26 |
+
ROOT = Path(__file__).parent
|
| 27 |
+
REPOS = ROOT / ".context/repos"
|
| 28 |
+
OUT = ROOT / ".context/out"
|
| 29 |
+
GITHUB = {"vllm": "vllm-project/vllm", "sglang": "sgl-project/sglang", "flashinfer": "flashinfer-ai/flashinfer"}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
# --------------------------------------------------------------------------- git helpers
|
| 33 |
+
def git(repo: str, *args: str) -> str:
|
| 34 |
+
return subprocess.run(["git", "-C", str(REPOS / repo), *args], capture_output=True, check=True).stdout.decode(
|
| 35 |
+
"utf-8", "replace"
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def ensure_clone(repo: str) -> None:
|
| 40 |
+
# Blobless clone: full history (commits+trees) but file contents are fetched on demand.
|
| 41 |
+
if not (REPOS / repo).exists():
|
| 42 |
+
REPOS.mkdir(parents=True, exist_ok=True)
|
| 43 |
+
subprocess.run(
|
| 44 |
+
["git", "clone", "-q", "--filter=blob:none", "--no-checkout", f"https://github.com/{GITHUB[repo]}", str(REPOS / repo)],
|
| 45 |
+
check=True,
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def fetch_blobs(repo: str, oids: list[str]) -> None:
|
| 50 |
+
# One round trip per 2k blobs instead of git's lazy one-blob-per-request fetch.
|
| 51 |
+
oids = sorted(set(oids))
|
| 52 |
+
for i in range(0, len(oids), 2000):
|
| 53 |
+
git(repo, "-c", "fetch.negotiationAlgorithm=noop", "fetch", "-q", "--no-tags", "--no-write-fetch-head",
|
| 54 |
+
"--filter=blob:none", "origin", *oids[i : i + 2000])
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def blob(repo: str, oid: str) -> str:
|
| 58 |
+
return git(repo, "cat-file", "-p", oid)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def ls_tree(repo: str, prefix: str) -> list[tuple[str, str]]:
|
| 62 |
+
"""(oid, path) for every file under prefix at HEAD."""
|
| 63 |
+
rows = [line.split(None, 3) for line in git(repo, "ls-tree", "-r", "HEAD", "--", prefix).splitlines()]
|
| 64 |
+
return [(r[2], r[3]) for r in rows if r[1] == "blob"]
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
LICENSE_RE = re.compile(r"SPDX-License-Identifier:\s*([^\n*]+)|(proprietary rights|TensorRT Source Code License)"
|
| 68 |
+
r"|(Apache License)|(Redistribution and use in source and binary forms)|(Permission is hereby granted)", re.I)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def file_license(code: str) -> str:
|
| 72 |
+
"""License declared in the file header; header-less files inherit their repo's Apache-2.0."""
|
| 73 |
+
m = LICENSE_RE.search(code[:5000])
|
| 74 |
+
if not m:
|
| 75 |
+
return "Apache-2.0"
|
| 76 |
+
spdx, proprietary, apache, bsd, mit = m.groups()
|
| 77 |
+
return spdx.strip() if spdx else "proprietary" if proprietary else "Apache-2.0" if apache else "BSD" if bsd else "MIT"
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def permissive(lic: str) -> bool:
|
| 81 |
+
return lic.startswith(("Apache-2.0", "BSD", "MIT"))
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
@functools.cache
|
| 85 |
+
def head_license(repo: str, path: str) -> str:
|
| 86 |
+
return file_license(git(repo, "show", f"HEAD:{path}"))
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def stage_licenses() -> Path:
|
| 90 |
+
"""Upstream LICENSE/NOTICE files: Apache-2.0 sec. 4 requires shipping them with redistributed code."""
|
| 91 |
+
for repo in GITHUB:
|
| 92 |
+
files = [(o, p) for o, p in ls_tree(repo, ".") if re.match(r"(LICENSE|NOTICE|licenses/)", p)]
|
| 93 |
+
fetch_blobs(repo, [o for o, _ in files])
|
| 94 |
+
for oid, p in files:
|
| 95 |
+
dst = OUT / "licenses" / repo / p
|
| 96 |
+
dst.parent.mkdir(parents=True, exist_ok=True)
|
| 97 |
+
dst.write_text(blob(repo, oid))
|
| 98 |
+
return OUT / "licenses"
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
# --------------------------------------------------------------------------- subset 1: tuned configs
|
| 102 |
+
CONFIG_DIRS = [
|
| 103 |
+
("vllm", "vllm/model_executor/layers/fused_moe/configs/"),
|
| 104 |
+
("vllm", "vllm/model_executor/layers/quantization/utils/configs/"),
|
| 105 |
+
("vllm", "vllm/model_executor/layers/mamba/ops/configs/selective_state_update/"),
|
| 106 |
+
("sglang", "python/sglang/srt/layers/moe/moe_runner/triton_utils/configs/"),
|
| 107 |
+
("sglang", "python/sglang/kernels/ops/gemm/configs/"),
|
| 108 |
+
]
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def pick_kernel(repo: str, cfg_dir: str, dtype: str, block_shape: str | None) -> tuple[str, str] | None:
|
| 112 |
+
"""Mirror each repo's runtime dispatch: (file, @triton.jit fn) that consumes this config, or None."""
|
| 113 |
+
if "moe" in cfg_dir:
|
| 114 |
+
f = {"vllm": "vllm/model_executor/layers/fused_moe/fused_moe.py",
|
| 115 |
+
"sglang": "python/sglang/kernels/ops/moe/fused_moe_triton_kernels.py"}[repo]
|
| 116 |
+
return f, "fused_moe_kernel_gptq_awq" if dtype.startswith("int4_w4a16") else "fused_moe_kernel"
|
| 117 |
+
if "mamba" in cfg_dir:
|
| 118 |
+
return "vllm/model_executor/layers/mamba/ops/mamba_ssm.py", "_selective_scan_update_kernel"
|
| 119 |
+
if not block_shape: # channelwise / bf16 GEMM configs feed other kernels
|
| 120 |
+
return None
|
| 121 |
+
if repo == "vllm": # vllm's int8 block configs are orphaned (kernel removed upstream)
|
| 122 |
+
return ("vllm/model_executor/layers/quantization/utils/fp8_utils.py", "_w8a8_triton_block_scaled_mm") \
|
| 123 |
+
if dtype.startswith("fp8") else None
|
| 124 |
+
if dtype.startswith("int8"):
|
| 125 |
+
return "python/sglang/kernels/ops/gemm/int8_kernel.py", "_w8a8_block_int8_matmul"
|
| 126 |
+
if dtype.startswith("fp8"):
|
| 127 |
+
return "python/sglang/kernels/ops/gemm/fp8_kernel.py", "_w8a8_block_fp8_matmul"
|
| 128 |
+
return None
|
| 129 |
+
# ponytail: hand-picked MoE models for shape->model matching; add repo ids here to widen coverage.
|
| 130 |
+
MOE_MODELS = [
|
| 131 |
+
"mistralai/Mixtral-8x7B-v0.1", "mistralai/Mixtral-8x22B-v0.1", "deepseek-ai/DeepSeek-V2-Lite",
|
| 132 |
+
"deepseek-ai/DeepSeek-V2", "deepseek-ai/DeepSeek-V3", "moonshotai/Kimi-K2-Instruct", "Qwen/Qwen1.5-MoE-A2.7B",
|
| 133 |
+
"Qwen/Qwen2-57B-A14B", "Qwen/Qwen3-30B-A3B", "Qwen/Qwen3-235B-A22B", "Qwen/Qwen3-Coder-480B-A35B-Instruct",
|
| 134 |
+
"Qwen/Qwen3-Next-80B-A3B-Instruct", "openai/gpt-oss-20b", "openai/gpt-oss-120b",
|
| 135 |
+
"meta-llama/Llama-4-Scout-17B-16E-Instruct", "meta-llama/Llama-4-Maverick-17B-128E-Instruct",
|
| 136 |
+
"databricks/dbrx-instruct", "allenai/OLMoE-1B-7B-0924", "ai21labs/AI21-Jamba-Mini-1.5", "zai-org/GLM-4.5",
|
| 137 |
+
"zai-org/GLM-4.5-Air", "zai-org/GLM-4.6", "MiniMaxAI/MiniMax-M2", "microsoft/Phi-3.5-MoE-instruct",
|
| 138 |
+
"baidu/ERNIE-4.5-21B-A3B-PT", "baidu/ERNIE-4.5-300B-A47B-PT", "tencent/Hunyuan-A13B-Instruct",
|
| 139 |
+
"ibm-granite/granite-3.1-3b-a800m-instruct", "deepseek-ai/deepseek-moe-16b-base", "jetmoe/jetmoe-8b",
|
| 140 |
+
"meituan-longcat/LongCat-Flash-Chat", "inclusionAI/Ling-lite-1.5", "XiaomiMiMo/MiMo-V2-Flash",
|
| 141 |
+
]
|
| 142 |
+
EXPERT_KEYS = ["num_local_experts", "n_routed_experts", "num_experts", "moe_num_experts"]
|
| 143 |
+
INTER_KEYS = ["moe_intermediate_size", "expert_ffn_hidden_size", "intermediate_size", "ffn_hidden_size"]
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def moe_shapes() -> dict[str, tuple[int, int]]:
|
| 147 |
+
"""model -> (num_experts, per-expert intermediate size), cached on disk."""
|
| 148 |
+
cache = OUT / "moe_models.json"
|
| 149 |
+
if cache.exists():
|
| 150 |
+
return {k: tuple(v) for k, v in json.loads(cache.read_text()).items()}
|
| 151 |
+
|
| 152 |
+
shapes = {}
|
| 153 |
+
for rid in MOE_MODELS:
|
| 154 |
+
try:
|
| 155 |
+
cfg = json.loads(Path(hf_hub_download(rid, "config.json")).read_text())
|
| 156 |
+
except Exception as e: # gated / renamed repos are just skipped
|
| 157 |
+
print(f" skip {rid}: {type(e).__name__}", file=sys.stderr)
|
| 158 |
+
continue
|
| 159 |
+
cfg = cfg.get("text_config") or cfg.get("ffn_config", {}) | cfg
|
| 160 |
+
e = next((cfg[k] for k in EXPERT_KEYS if isinstance(cfg.get(k), int)), None)
|
| 161 |
+
n = next((cfg[k] for k in INTER_KEYS if isinstance(cfg.get(k), int)), None)
|
| 162 |
+
if e and n:
|
| 163 |
+
shapes[rid.split("/")[1]] = (e, n)
|
| 164 |
+
cache.write_text(json.dumps(shapes, indent=1))
|
| 165 |
+
return shapes
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def match_models(E: int, N: int, shapes: dict) -> list[str]:
|
| 169 |
+
"""Models whose MoE layer yields this (E, N) under tensor parallel (N=I/tp) or expert parallel (E=experts/ep)."""
|
| 170 |
+
out = []
|
| 171 |
+
for name, (experts, inter) in shapes.items():
|
| 172 |
+
out += [f"{name} (TP{tp})" for tp in (1, 2, 4, 8, 16) if E == experts and N * tp == inter]
|
| 173 |
+
out += [f"{name} (EP{ep})" for ep in (2, 4, 8, 16, 32) if N == inter and E * ep == experts]
|
| 174 |
+
return out
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def parse_config_name(name: str) -> dict:
|
| 178 |
+
"""'E=8,N=14336,device_name=NVIDIA_H100,block_shape=[128, 128].json' -> dict."""
|
| 179 |
+
return {k: v for k, v in re.findall(r"(\w+)=(\[[^\]]*\]|[^,]+)", name.removesuffix(".json"))}
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
@functools.cache
|
| 183 |
+
def kernel_source(repo: str, path: str, fn: str) -> str | None:
|
| 184 |
+
code = git(repo, "show", f"HEAD:{path}")
|
| 185 |
+
for node in ast.walk(ast.parse(code)):
|
| 186 |
+
if isinstance(node, ast.FunctionDef) and node.name == fn:
|
| 187 |
+
start = min([d.lineno for d in node.decorator_list] + [node.lineno])
|
| 188 |
+
return "\n".join(code.splitlines()[start - 1 : node.end_lineno])
|
| 189 |
+
return None
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def config_prompt(r: dict) -> str:
|
| 193 |
+
spec = "\n".join(f"- {k}: {v}" for k, v in r["shape"].items())
|
| 194 |
+
models = ", ".join(r["candidate_models"]) or "unknown"
|
| 195 |
+
return (
|
| 196 |
+
f"You are tuning the Triton kernel `{r['kernel_name']}` (from {r['repo']}) for one deployment.\n\n"
|
| 197 |
+
f"Hardware: {r['device_name']}\nQuant dtype: {r['dtype']}\nProblem shape:\n{spec}\n"
|
| 198 |
+
f"Batch size (tokens, M): {r['M']}\nModels with this shape: {models}\n\n"
|
| 199 |
+
f"Kernel source:\n```python\n{r['kernel_source']}\n```\n\n"
|
| 200 |
+
f"Pick the fastest launch configuration. Answer with a JSON object with exactly these keys: "
|
| 201 |
+
f"{', '.join(json.loads(r['best_config']))}."
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def config_prs(repo: str, prefix: str) -> dict[str, tuple[int | None, int]]:
|
| 206 |
+
"""config path -> (PR of the newest commit that added/changed it, #config files that commit touched)."""
|
| 207 |
+
log = git(repo, "log", "--no-renames", "--diff-filter=AM", "--format=%x00%s", "--name-only", "--", prefix)
|
| 208 |
+
out = {}
|
| 209 |
+
for chunk in log.split("\x00")[1:]:
|
| 210 |
+
subject, *paths = [l for l in chunk.splitlines() if l]
|
| 211 |
+
pr = re.search(r"\(#(\d+)\)\s*$", subject)
|
| 212 |
+
for p in paths:
|
| 213 |
+
out.setdefault(p, (int(pr[1]) if pr else None, len(paths)))
|
| 214 |
+
return out
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def same_gpu(hw: str | None, device: str) -> bool:
|
| 218 |
+
"""Token match: 'H100' ~ 'NVIDIA_H100_80GB_HBM3', but 'H20' never matches 'NVIDIA_H200'."""
|
| 219 |
+
toks = lambda s: set(re.split(r"[^A-Z0-9]+", s.upper())) - {"", "NVIDIA", "AMD", "INSTINCT"}
|
| 220 |
+
return bool(hw) and toks(hw) <= toks(device)
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def shape_ok(shape: str | None, meta: dict) -> bool:
|
| 224 |
+
"""No key=value in the measurement's shape contradicts the config's own (E, N, K, headdim, ...)."""
|
| 225 |
+
got = {k.lower(): v for k, v in re.findall(r"(\w+)\s*=\s*([^,;\s]+)", shape or "")}
|
| 226 |
+
return all(got[k.lower()] == str(v) for k, v in meta.items() if k.lower() in got)
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def gain_at(ms: list[dict], M: int, device: str, meta: dict, n_files: int) -> float | None:
|
| 230 |
+
"""Documented kernel speedup of the tuned config over the default at batch size M, only when unambiguous."""
|
| 231 |
+
c = [m for m in ms if m.get("scope") == "kernel" and m.get("batch_size") == M and shape_ok(m.get("shape"), meta)]
|
| 232 |
+
if n_files > 1: # PR tuned several files: only trust rows that name this GPU
|
| 233 |
+
c = [m for m in c if same_gpu(m.get("hardware"), device)]
|
| 234 |
+
s = [m["speedup"] for m in c]
|
| 235 |
+
# rows that disagree (e.g. per-dtype tables the extractor didn't label) -> don't guess
|
| 236 |
+
return round(statistics.median(s), 4) if s and max(s) / min(s) <= 1.05 else None
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def build_tuned_configs() -> list[dict]:
|
| 240 |
+
shapes = moe_shapes()
|
| 241 |
+
print(f" {len(shapes)} MoE model shapes", file=sys.stderr)
|
| 242 |
+
rows = []
|
| 243 |
+
for repo, prefix in CONFIG_DIRS:
|
| 244 |
+
files = [(o, p) for o, p in ls_tree(repo, prefix) if p.endswith(".json")]
|
| 245 |
+
fetch_blobs(repo, [o for o, _ in files])
|
| 246 |
+
sha = git(repo, "rev-parse", "HEAD").strip()
|
| 247 |
+
prs = config_prs(repo, prefix)
|
| 248 |
+
for oid, path in files:
|
| 249 |
+
pr, n_files = prs.get(path, (None, 0))
|
| 250 |
+
meta = parse_config_name(Path(path).name)
|
| 251 |
+
dtype = meta.pop("dtype", "bf16/fp16")
|
| 252 |
+
device = meta.pop("device_name", None)
|
| 253 |
+
block_shape = meta.pop("block_shape", None)
|
| 254 |
+
kernel = pick_kernel(repo, prefix, dtype, block_shape)
|
| 255 |
+
src = kernel and kernel_source(repo, *kernel)
|
| 256 |
+
if not device or not src:
|
| 257 |
+
print(f" skip {path}: no device or kernel {kernel}", file=sys.stderr)
|
| 258 |
+
continue
|
| 259 |
+
kfile, kfn = kernel
|
| 260 |
+
if not permissive(head_license(repo, kfile)):
|
| 261 |
+
continue
|
| 262 |
+
table = json.loads(blob(repo, oid))
|
| 263 |
+
triton_dir = re.search(r"triton_(\d+_\d+_\d+)", path)
|
| 264 |
+
triton_ver = table.pop("triton_version", None) or (triton_dir and triton_dir[1].replace("_", "."))
|
| 265 |
+
E, N = meta.get("E"), meta.get("N")
|
| 266 |
+
cands = match_models(int(E), int(N), shapes) if E and N and "fused_moe" in kfn else []
|
| 267 |
+
for M, cfg in table.items():
|
| 268 |
+
if not M.isdigit() or not isinstance(cfg, dict):
|
| 269 |
+
continue
|
| 270 |
+
r = dict(
|
| 271 |
+
repo=repo, commit=sha, config_path=path, kernel_file=kfile, kernel_name=kfn,
|
| 272 |
+
kernel_source=src, license=head_license(repo, kfile), device_name=device, dtype=dtype, block_shape=block_shape,
|
| 273 |
+
triton_version=triton_ver, shape=meta, M=int(M), candidate_models=cands,
|
| 274 |
+
best_config=json.dumps(cfg), config_pr=pr, config_pr_files=n_files,
|
| 275 |
+
# group by basename so the same shape (any repo / triton version / M) never straddles splits
|
| 276 |
+
split="test" if int(hashlib.md5(Path(path).name.encode()).hexdigest(), 16) % 10 == 0 else "train",
|
| 277 |
+
)
|
| 278 |
+
r["prompt"] = config_prompt(r)
|
| 279 |
+
r["shape"] = json.dumps(meta)
|
| 280 |
+
rows.append(r)
|
| 281 |
+
print(f" {repo}:{prefix} -> {len(rows)} rows so far", file=sys.stderr)
|
| 282 |
+
docs = gains.fetch_all({(GITHUB[r["repo"]], r["config_pr"]): Path(r["config_path"]).name for r in rows if r["config_pr"]})
|
| 283 |
+
for r in rows:
|
| 284 |
+
pr, n_files = r.pop("config_pr"), r.pop("config_pr_files")
|
| 285 |
+
ms = docs[(GITHUB[r["repo"]], pr)][1] if pr else []
|
| 286 |
+
r["config_pr_url"] = f"https://github.com/{GITHUB[r['repo']]}/pull/{pr}" if pr else None
|
| 287 |
+
r["config_pr_gains"] = json.dumps(ms)
|
| 288 |
+
r["speedup_vs_default"] = gain_at(ms, r["M"], r["device_name"], json.loads(r["shape"]), n_files)
|
| 289 |
+
return rows
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
# --------------------------------------------------------------------------- subset 2: kernel commits
|
| 293 |
+
KERNEL_PATHS = {
|
| 294 |
+
"vllm": ["csrc", "vllm/model_executor/layers", "vllm/attention", "vllm/v1/attention", "vllm/kernels"],
|
| 295 |
+
"sglang": ["sgl-kernel", "python/sglang/srt/layers", "python/sglang/kernels"],
|
| 296 |
+
"flashinfer": ["include", "csrc", "flashinfer"],
|
| 297 |
+
}
|
| 298 |
+
PERF_GREP = r"\[perf\]|optimi|speed ?up|faster|perf|tune|tuning|accelerat|throughput|latency"
|
| 299 |
+
PERF_TITLE = re.compile(PERF_GREP, re.I) # git --grep also hits PR bodies; require the signal in the title
|
| 300 |
+
SKIP_TITLE = re.compile(r"^revert|\[(build|ci|ci/build|doc|docs|test|tests|misc)\]|compil|\bjit\b|wheel|\bci\b", re.I)
|
| 301 |
+
SKIP_PATH = re.compile(r"(^|/)(tests?|benchmarks?|docs?|examples?|configs?)/")
|
| 302 |
+
LANG = {".cu": "cuda", ".cuh": "cuda", ".cpp": "cpp", ".cc": "cpp", ".h": "cpp", ".hpp": "cpp", ".py": "python"}
|
| 303 |
+
MAX_FILES_PER_COMMIT, MAX_BYTES, MAX_CHANGED = 10, 120_000, 800
|
| 304 |
+
FAMILIES = {
|
| 305 |
+
"deepseek": r"deep ?seek|\bdsv\d|\bds-?v\d|\bds-?r1\b", "qwen": r"qwen", "llama": r"llama", "mixtral": r"mixtral",
|
| 306 |
+
"mistral": r"mistral|ministral", "kimi": r"kimi|moonshot", "glm": r"\bglm", "gpt-oss": r"gpt-?oss",
|
| 307 |
+
"gemma": r"gemma", "minimax": r"minimax", "mamba": r"mamba|nemotron-?h\b", "nemotron": r"nemotron",
|
| 308 |
+
"phi": r"\bphi-?\d", "grok": r"grok", "ernie": r"ernie", "hunyuan": r"hunyuan", "jamba": r"jamba",
|
| 309 |
+
"dbrx": r"dbrx", "olmo": r"olmo", "granite": r"granite", "llava/vlm": r"llava|\bvlm\b|\bvision\b",
|
| 310 |
+
}
|
| 311 |
+
HW_RE = re.compile(
|
| 312 |
+
r"\b(H(?:20|100|200|800)|GB?[23]00|B[23]00|A100|A10G?|L40S?|L4|RTX ?\d{4}|MI3\d{2}X?|gfx\d{3,4}|sm_?\d{2,3}a?"
|
| 313 |
+
r"|hopper|blackwell|ampere|ada|xpu|cpu|tpu|gaudi)\b", re.I)
|
| 314 |
+
SPEEDUP_RE = re.compile(r"\b\d+(?:\.\d+)?\s?[x×](?![\w\d])")
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def kernel_lang(path: str, code: str) -> str | None:
|
| 318 |
+
lang = LANG.get(Path(path).suffix)
|
| 319 |
+
if lang != "python":
|
| 320 |
+
return lang
|
| 321 |
+
if "@triton.jit" in code or "@triton.autotune" in code:
|
| 322 |
+
return "triton"
|
| 323 |
+
if "cutlass.cute" in code or "@cute.kernel" in code:
|
| 324 |
+
return "cute_dsl"
|
| 325 |
+
return None # plain Python glue isn't a kernel
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def tags(text: str) -> tuple[list[str], list[str], list[str]]:
|
| 329 |
+
low = text.lower()
|
| 330 |
+
models = [f for f, rx in FAMILIES.items() if re.search(rx, low)]
|
| 331 |
+
hw = sorted({re.sub(r"^(SM\d+)A$", r"\1", re.sub(r"[ _]", "", h.upper())) for h in HW_RE.findall(text)})
|
| 332 |
+
return models, hw, SPEEDUP_RE.findall(text)[:10]
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
def perf_commits(repo: str) -> list[dict]:
|
| 336 |
+
log = git(repo, "log", "--no-merges", "--no-renames", "-i", "-E", f"--grep={PERF_GREP}",
|
| 337 |
+
"--format=%x00%H%x1f%aI%x1f%B%x1e", "--raw", "--no-abbrev", "--", *KERNEL_PATHS[repo])
|
| 338 |
+
commits = []
|
| 339 |
+
for chunk in log.split("\x00")[1:]:
|
| 340 |
+
head, raw = chunk.split("\x1e", 1)
|
| 341 |
+
sha, date, msg = head.split("\x1f", 2)
|
| 342 |
+
title = msg.strip().splitlines()[0]
|
| 343 |
+
if not PERF_TITLE.search(title) or SKIP_TITLE.search(title):
|
| 344 |
+
continue
|
| 345 |
+
files = []
|
| 346 |
+
for line in raw.strip().splitlines():
|
| 347 |
+
meta, path = line.split("\t", 1)
|
| 348 |
+
_, _, old, new, status = meta.split()
|
| 349 |
+
if status == "M" and Path(path).suffix in LANG and not SKIP_PATH.search(path):
|
| 350 |
+
files.append((path, old, new))
|
| 351 |
+
if 0 < len(files) <= MAX_FILES_PER_COMMIT:
|
| 352 |
+
commits.append(dict(sha=sha, date=date, msg=msg.strip(), files=files))
|
| 353 |
+
return commits
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
EDIT_FORMAT = """Respond with one or more edits to the file, each in exactly this format:
|
| 357 |
+
<<<<<<< SEARCH
|
| 358 |
+
(exact, contiguous lines copied from the current file)
|
| 359 |
+
=======
|
| 360 |
+
(the replacement lines)
|
| 361 |
+
>>>>>>> REPLACE"""
|
| 362 |
+
FENCE = {"cuda": "cuda", "cpp": "cpp", "triton": "python", "cute_dsl": "python"}
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
def commit_prompt(r: dict) -> str:
|
| 366 |
+
# the PR title is the task statement (like the issue in SWE-RL); the PR body is withheld since it describes the fix
|
| 367 |
+
goal = re.sub(r"\s*\(#\d+\)\s*$", "", r["title"])
|
| 368 |
+
return (
|
| 369 |
+
f"Optimize this {r['language']} kernel file from {r['repo']} ({r['path']}).\n\n"
|
| 370 |
+
f"Goal: {goal}\nTarget hardware: {', '.join(r['hardware_mentioned']) or 'unspecified'}\n"
|
| 371 |
+
f"Target models: {', '.join(r['models_mentioned']) or 'unspecified'}\n\n"
|
| 372 |
+
f"Current file:\n```{FENCE[r['language']]}\n{r['before_code']}\n```\n\n{EDIT_FORMAT}"
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
def build_kernel_commits() -> list[dict]:
|
| 377 |
+
rows = []
|
| 378 |
+
for repo in KERNEL_PATHS:
|
| 379 |
+
commits = perf_commits(repo)
|
| 380 |
+
fetch_blobs(repo, [o for c in commits for _, a, b in c["files"] for o in (a, b)])
|
| 381 |
+
for c in commits:
|
| 382 |
+
title = c["msg"].splitlines()[0]
|
| 383 |
+
pr = re.search(r"\(#(\d+)\)", title)
|
| 384 |
+
for path, old, new in c["files"]:
|
| 385 |
+
before, after = blob(repo, old), blob(repo, new)
|
| 386 |
+
lang = kernel_lang(path, after)
|
| 387 |
+
lic = file_license(after)
|
| 388 |
+
if not lang or max(len(before), len(after)) > MAX_BYTES or not (permissive(lic) and permissive(file_license(before))):
|
| 389 |
+
continue
|
| 390 |
+
diff = list(difflib.unified_diff(before.splitlines(), after.splitlines(), path, path, lineterm=""))
|
| 391 |
+
added = sum(1 for l in diff if l.startswith("+") and not l.startswith("+++"))
|
| 392 |
+
removed = sum(1 for l in diff if l.startswith("-") and not l.startswith("---"))
|
| 393 |
+
if not 0 < added + removed <= MAX_CHANGED:
|
| 394 |
+
continue
|
| 395 |
+
models, hw, speedups = tags(c["msg"] + "\n" + path)
|
| 396 |
+
rows.append(dict(
|
| 397 |
+
repo=repo, commit=c["sha"], date=c["date"], pr_number=int(pr[1]) if pr else None,
|
| 398 |
+
pr_url=f"https://github.com/{GITHUB[repo]}/pull/{pr[1]}" if pr else None,
|
| 399 |
+
title=title, message=c["msg"][:8000], path=path, language=lang, license=lic,
|
| 400 |
+
before_code=before, after_code=after, diff="\n".join(diff),
|
| 401 |
+
lines_added=added, lines_removed=removed, files_in_commit=len(c["files"]),
|
| 402 |
+
models_mentioned=models, hardware_mentioned=hw, speedup_claims=speedups,
|
| 403 |
+
))
|
| 404 |
+
rows[-1]["prompt"] = commit_prompt(rows[-1])
|
| 405 |
+
print(f" {repo}: {len(commits)} commits -> {len(rows)} rows so far", file=sys.stderr)
|
| 406 |
+
docs = gains.fetch_all({(GITHUB[r["repo"]], r["pr_number"]): r["title"] for r in rows if r["pr_number"]})
|
| 407 |
+
for r in rows:
|
| 408 |
+
body, ms = docs[(GITHUB[r["repo"]], r["pr_number"])] if r["pr_number"] else ("", [])
|
| 409 |
+
r |= dict(pr_body=body[:gains.MAX_BODY], gains=json.dumps(ms),
|
| 410 |
+
kernel_speedup=gains.summarize(ms, "kernel"), e2e_speedup=gains.summarize(ms, "e2e"))
|
| 411 |
+
# temporal split: newest ~10% of commits is test (closest to post-training-cutoff code)
|
| 412 |
+
cutoff = sorted(r["date"] for r in rows)[int(len(rows) * 0.9)]
|
| 413 |
+
for r in rows:
|
| 414 |
+
r["split"] = "test" if r["date"] >= cutoff else "train"
|
| 415 |
+
return rows
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
# --------------------------------------------------------------------------- main
|
| 419 |
+
def to_dd(rows: list[dict]) -> DatasetDict:
|
| 420 |
+
return DatasetDict({s: Dataset.from_list([{k: v for k, v in r.items() if k != "split"} for r in rows if r["split"] == s])
|
| 421 |
+
for s in ("train", "test")})
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
if __name__ == "__main__":
|
| 425 |
+
OUT.mkdir(parents=True, exist_ok=True)
|
| 426 |
+
for repo in GITHUB:
|
| 427 |
+
ensure_clone(repo)
|
| 428 |
+
if "--from-disk" in sys.argv: # push the last build (e.g. after editing only the card)
|
| 429 |
+
subsets = {name: load_from_disk(OUT / name) for name in ("tuned_configs", "kernel_commits")}
|
| 430 |
+
else:
|
| 431 |
+
subsets = {"tuned_configs": to_dd(build_tuned_configs()), "kernel_commits": to_dd(build_kernel_commits())}
|
| 432 |
+
for name, dd in subsets.items():
|
| 433 |
+
print(name, dd, file=sys.stderr)
|
| 434 |
+
dd.save_to_disk(OUT / name)
|
| 435 |
+
if "--push" in sys.argv:
|
| 436 |
+
repo_id = sys.argv[sys.argv.index("--push") + 1]
|
| 437 |
+
for name, dd in subsets.items():
|
| 438 |
+
dd.push_to_hub(repo_id, config_name=name)
|
| 439 |
+
HfApi().upload_folder(folder_path=stage_licenses(), path_in_repo="licenses", repo_id=repo_id, repo_type="dataset")
|
| 440 |
+
HfApi().upload_folder(folder_path=ROOT, path_in_repo="code", repo_id=repo_id, repo_type="dataset",
|
| 441 |
+
allow_patterns=["build.py", "gains.py", "reward.py", "test_build.py", "pyproject.toml", "uv.lock"])
|
| 442 |
+
# our card carries the `configs:` YAML, so it replaces the auto-generated one
|
| 443 |
+
HfApi().upload_file(path_or_fileobj=ROOT / "README.md", path_in_repo="README.md", repo_id=repo_id, repo_type="dataset")
|
code/gains.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Benchmark gains documented in PR descriptions: fetch bodies (gh) and extract measurements (LLM, HF Inference)."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import re
|
| 5 |
+
import statistics
|
| 6 |
+
import subprocess
|
| 7 |
+
import sys
|
| 8 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
from huggingface_hub import InferenceClient
|
| 12 |
+
|
| 13 |
+
CACHE = Path(__file__).parent / ".context/prs"
|
| 14 |
+
MODEL = "Qwen/Qwen3-235B-A22B-Instruct-2507"
|
| 15 |
+
FALLBACK = "openai/gpt-oss-120b:cerebras" # ~40x faster; for dense tables that exceed the 120s gateway timeout
|
| 16 |
+
MAX_BODY = 24_000 # stored in the dataset
|
| 17 |
+
MAX_SOURCE, CHUNK = 80_000, 4_000 # read for extraction, per LLM call
|
| 18 |
+
# cheap prefilter: skip the LLM when the body has no perf numbers at all
|
| 19 |
+
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)
|
| 20 |
+
|
| 21 |
+
PROMPT = """Extract the performance measurements from this GitHub pull request description of a GPU kernel change.
|
| 22 |
+
|
| 23 |
+
Only extract before-vs-after comparisons where the baseline is the code/config BEFORE this PR (main, default config, \
|
| 24 |
+
previous kernel, "before") and the optimized side is THIS PR ("after", "tuned", "PR"). Skip comparisons against other \
|
| 25 |
+
libraries or alternatives, accuracy/eval scores, and anything not explicitly in the text. Never invent or compute numbers.
|
| 26 |
+
|
| 27 |
+
Return JSON: {{"measurements": [{{
|
| 28 |
+
"scope": "kernel" | "e2e", // kernel micro-benchmark vs end-to-end serving/model benchmark
|
| 29 |
+
"hardware": str | null, // e.g. "H100", "B200", "MI300X"
|
| 30 |
+
"model": str | null, // e.g. "DeepSeek-V3"
|
| 31 |
+
"shape": str | null, // other shape params, e.g. "N=7168,K=2048" or "hidden=4096"
|
| 32 |
+
"batch_size": int | null, // batch size / num tokens / M, if the row has one
|
| 33 |
+
"metric": str, // e.g. "latency", "throughput", "TFLOPS"
|
| 34 |
+
"unit": str | null, // e.g. "us", "tok/s"
|
| 35 |
+
"higher_is_better": bool, // false for latency/time, true for throughput/TFLOPS/bandwidth
|
| 36 |
+
"baseline": number | null,
|
| 37 |
+
"optimized": number | null,
|
| 38 |
+
"stated_speedup": number | null // ONLY if the text states a speedup ratio without raw values (e.g. "1.3x" -> 1.3, "+20%" -> 1.2)
|
| 39 |
+
}}]}}
|
| 40 |
+
Return {{"measurements": []}} if there are none. One entry per table row / reported number.
|
| 41 |
+
|
| 42 |
+
PR title: {title}
|
| 43 |
+
|
| 44 |
+
PR description:
|
| 45 |
+
{body}"""
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _key(repo: str, n: int) -> str:
|
| 49 |
+
return f"{repo.replace('/', '__')}-{n}"
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def pr_body(repo: str, n: int) -> str | None:
|
| 53 |
+
"""PR description, or None if the fetch failed (so callers don't cache a fake empty body)."""
|
| 54 |
+
f = CACHE / f"{_key(repo, n)}.md"
|
| 55 |
+
if not f.exists():
|
| 56 |
+
r = subprocess.run(["gh", "api", f"repos/{repo}/pulls/{n}", "--jq", '.body // ""'], capture_output=True, text=True)
|
| 57 |
+
if r.returncode and "404" not in r.stderr: # not cached: transient errors (rate limit) retry next build
|
| 58 |
+
print(f" gh {repo}#{n}: {r.stderr.strip()[:100]}", file=sys.stderr)
|
| 59 |
+
return None
|
| 60 |
+
f.write_text(r.stdout if not r.returncode else "") # 404 = "(#n)" was an issue, not a PR
|
| 61 |
+
return f.read_text()
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def speedup(m: dict) -> float | None:
|
| 65 |
+
"""Normalized so > 1 means this PR is better."""
|
| 66 |
+
b, o = m.get("baseline"), m.get("optimized")
|
| 67 |
+
if isinstance(b, (int, float)) and isinstance(o, (int, float)) and b > 0 and o > 0:
|
| 68 |
+
return round(o / b if m.get("higher_is_better") else b / o, 4)
|
| 69 |
+
s = m.get("stated_speedup")
|
| 70 |
+
return float(s) if isinstance(s, (int, float)) and s > 0 else None
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def chunks(body: str) -> list[str]:
|
| 74 |
+
"""Split on blank lines into <= CHUNK pieces: one call per long benchmark table section stays under the
|
| 75 |
+
gateway timeout. An oversized paragraph (a giant table) is split by lines, repeating its 2 header lines."""
|
| 76 |
+
out = [""]
|
| 77 |
+
for para in body[:MAX_SOURCE].split("\n\n"):
|
| 78 |
+
lines = para.splitlines()
|
| 79 |
+
pieces = [para] if len(para) <= CHUNK else [
|
| 80 |
+
"\n".join(lines[:2] + lines[i : i + 60]) for i in range(2, len(lines), 60)]
|
| 81 |
+
for p in pieces:
|
| 82 |
+
if out[-1] and len(out[-1]) + len(p) > CHUNK:
|
| 83 |
+
out.append("")
|
| 84 |
+
out[-1] += p + "\n\n"
|
| 85 |
+
return out
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def _llm(client: InferenceClient, content: str) -> list[dict]:
|
| 89 |
+
for attempt, model in enumerate([MODEL, FALLBACK, FALLBACK]): # gateway 5xx/timeouts are common
|
| 90 |
+
try:
|
| 91 |
+
r = client.chat_completion(model=model, max_tokens=16000, temperature=0, response_format={"type": "json_object"},
|
| 92 |
+
messages=[{"role": "user", "content": content}])
|
| 93 |
+
return json.loads(r.choices[0].message.content)["measurements"]
|
| 94 |
+
except Exception:
|
| 95 |
+
if attempt == 2:
|
| 96 |
+
raise
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def extract(repo: str, n: int, title: str, client: InferenceClient) -> list[dict]:
|
| 100 |
+
f = CACHE / f"{_key(repo, n)}.gains.json"
|
| 101 |
+
if f.exists():
|
| 102 |
+
return json.loads(f.read_text())
|
| 103 |
+
body = pr_body(repo, n)
|
| 104 |
+
if body is None:
|
| 105 |
+
return []
|
| 106 |
+
ms = []
|
| 107 |
+
if HAS_NUMBERS.search(body):
|
| 108 |
+
parts = chunks(body)
|
| 109 |
+
try:
|
| 110 |
+
for i, part in enumerate(parts):
|
| 111 |
+
ctx = "" if i == 0 else f"(Part {i + 1}/{len(parts)}. For context only, the description starts: " \
|
| 112 |
+
f"{body[:1200]!r}. Extract ONLY from the part below.)\n\n"
|
| 113 |
+
ms += _llm(client, PROMPT.format(title=title, body=ctx + part))
|
| 114 |
+
except Exception as e: # not cached: retry on the next build
|
| 115 |
+
print(f" llm {repo}#{n}: {type(e).__name__} {str(e)[:100]}", file=sys.stderr)
|
| 116 |
+
return []
|
| 117 |
+
ms = [m | {"speedup": speedup(m)} for m in ms if isinstance(m, dict)]
|
| 118 |
+
ms = [m for m in ms if m["speedup"] and 0.01 < m["speedup"] < 1000] # drop unparseable / absurd rows
|
| 119 |
+
f.write_text(json.dumps(ms))
|
| 120 |
+
return ms
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def fetch_all(prs: dict[tuple[str, int], str], workers: int = 24) -> dict[tuple[str, int], tuple[str, list[dict]]]:
|
| 124 |
+
"""{(gh_repo, pr): title} -> {(gh_repo, pr): (body, measurements)}"""
|
| 125 |
+
CACHE.mkdir(parents=True, exist_ok=True)
|
| 126 |
+
client = InferenceClient()
|
| 127 |
+
keys = sorted(prs)
|
| 128 |
+
with ThreadPoolExecutor(workers) as ex:
|
| 129 |
+
bodies = list(ex.map(lambda k: pr_body(*k), keys))
|
| 130 |
+
gains = list(ex.map(lambda k: extract(*k, prs[k], client), keys))
|
| 131 |
+
print(f" PRs: {len(keys)}, with gains: {sum(bool(g) for g in gains)}", file=sys.stderr)
|
| 132 |
+
return {k: (b or "", g) for k, b, g in zip(keys, bodies, gains)}
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def summarize(ms: list[dict], scope: str) -> float | None:
|
| 136 |
+
s = [m["speedup"] for m in ms if m.get("scope") == scope]
|
| 137 |
+
return round(statistics.median(s), 4) if s else None
|
code/pyproject.toml
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[project]
|
| 2 |
+
name = "kernel-opt-rl"
|
| 3 |
+
version = "0.1.0"
|
| 4 |
+
requires-python = ">=3.13"
|
| 5 |
+
dependencies = [
|
| 6 |
+
"datasets>=5.1.0",
|
| 7 |
+
"huggingface-hub>=2.2.0",
|
| 8 |
+
]
|
code/reward.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Offline rewards (no GPU needed) for both subsets.
|
| 2 |
+
|
| 3 |
+
With a GPU, the real reward is measured latency (or run the task through KernelGYM).
|
| 4 |
+
These are the cheap proxies for rollouts without hardware.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import difflib
|
| 8 |
+
import json
|
| 9 |
+
import re
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# --------------------------------------------------------------------------- tuned_configs
|
| 13 |
+
def parse_answer(completion: str) -> dict | None:
|
| 14 |
+
"""Last parseable flat JSON object in the completion."""
|
| 15 |
+
for m in reversed(re.findall(r"\{[^{}]*\}", completion)):
|
| 16 |
+
try:
|
| 17 |
+
return json.loads(m)
|
| 18 |
+
except json.JSONDecodeError:
|
| 19 |
+
pass
|
| 20 |
+
return None
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def config_reward(pred: dict | None, best: dict) -> float:
|
| 24 |
+
"""Score a predicted launch config against the autotuned best config, in [0, 1].
|
| 25 |
+
|
| 26 |
+
`best` example: {"BLOCK_SIZE_M": 16, "BLOCK_SIZE_N": 64, "BLOCK_SIZE_K": 128,
|
| 27 |
+
"GROUP_SIZE_M": 1, "num_warps": 4, "num_stages": 5}
|
| 28 |
+
"""
|
| 29 |
+
# TODO(you): define the partial-credit scheme.
|
| 30 |
+
raise NotImplementedError
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def reward(completion: str, best_config: str) -> float:
|
| 34 |
+
return config_reward(parse_answer(completion), json.loads(best_config))
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
# --------------------------------------------------------------------------- kernel_commits
|
| 38 |
+
EDIT_RE = re.compile(r"<<<<<<< SEARCH\n(.*?)\n=======\n(.*?)\n?>>>>>>> REPLACE", re.S)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def apply_edits(code: str, completion: str) -> str | None:
|
| 42 |
+
"""Apply SEARCH/REPLACE blocks in order; None if there are none or any SEARCH text isn't in the file."""
|
| 43 |
+
edits = EDIT_RE.findall(completion)
|
| 44 |
+
if not edits:
|
| 45 |
+
return None
|
| 46 |
+
for search, replace in edits:
|
| 47 |
+
if search not in code:
|
| 48 |
+
return None
|
| 49 |
+
code = code.replace(search, replace, 1)
|
| 50 |
+
return code
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _changed_lines(before: str, after: str) -> str:
|
| 54 |
+
diff = difflib.unified_diff(before.splitlines(), after.splitlines(), lineterm="", n=0)
|
| 55 |
+
return "\n".join(l for l in diff if l[:1] in "+-" and not l.startswith(("+++", "---")))
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def patch_reward(completion: str, before_code: str, after_code: str) -> float:
|
| 59 |
+
"""SWE-RL-style: -1 for malformed/inapplicable edits, else similarity of the changed lines to the real commit's."""
|
| 60 |
+
pred = apply_edits(before_code, completion)
|
| 61 |
+
if pred is None:
|
| 62 |
+
return -1.0
|
| 63 |
+
return difflib.SequenceMatcher(None, _changed_lines(before_code, pred), _changed_lines(before_code, after_code)).ratio()
|
code/test_build.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from build import match_models, parse_config_name, pick_kernel, tags
|
| 2 |
+
|
| 3 |
+
assert parse_config_name("E=8,N=14336,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8,block_shape=[128, 128].json") == {
|
| 4 |
+
"E": "8", "N": "14336", "device_name": "NVIDIA_H100_80GB_HBM3", "dtype": "fp8_w8a8", "block_shape": "[128, 128]"}
|
| 5 |
+
|
| 6 |
+
shapes = {"Mixtral-8x7B-v0.1": (8, 14336), "DeepSeek-V3": (256, 2048)}
|
| 7 |
+
assert match_models(8, 7168, shapes) == ["Mixtral-8x7B-v0.1 (TP2)"]
|
| 8 |
+
assert match_models(32, 2048, shapes) == ["DeepSeek-V3 (EP8)"]
|
| 9 |
+
assert match_models(8, 1000, shapes) == []
|
| 10 |
+
|
| 11 |
+
moe = "vllm/model_executor/layers/fused_moe/configs/"
|
| 12 |
+
assert pick_kernel("vllm", moe, "int4_w4a16", None)[1] == "fused_moe_kernel_gptq_awq"
|
| 13 |
+
assert pick_kernel("vllm", moe, "fp8_w8a8", "[128,128]")[1] == "fused_moe_kernel"
|
| 14 |
+
gemm = "python/sglang/kernels/ops/gemm/configs/"
|
| 15 |
+
assert pick_kernel("sglang", gemm, "int8_w8a8", "[128,128]")[1] == "_w8a8_block_int8_matmul"
|
| 16 |
+
assert pick_kernel("sglang", gemm, "fp8_w8a8_channelwise", None) is None
|
| 17 |
+
assert pick_kernel("vllm", "vllm/model_executor/layers/quantization/utils/configs/", "int8_w8a8", "[128,128]") is None
|
| 18 |
+
|
| 19 |
+
models, hw, speed = tags("[Perf] DeepSeek-V3 MLA decode 1.8x faster on H200 / B200 (#123)")
|
| 20 |
+
assert models == ["deepseek"] and hw == ["B200", "H200"] and speed == ["1.8x"], (models, hw, speed)
|
| 21 |
+
assert tags("sm_100a and SM100 kernels for revision 2")[:2] == ([], ["SM100"])
|
| 22 |
+
|
| 23 |
+
from build import gain_at, same_gpu
|
| 24 |
+
from gains import speedup
|
| 25 |
+
assert same_gpu("H100", "NVIDIA_H100_80GB_HBM3") and same_gpu("NVIDIA H20-3e", "NVIDIA_H20-3e")
|
| 26 |
+
assert not same_gpu("H20", "NVIDIA_H200") and not same_gpu(None, "NVIDIA_H200")
|
| 27 |
+
assert speedup({"baseline": 10, "optimized": 5, "higher_is_better": False}) == 2.0 # latency halves
|
| 28 |
+
assert speedup({"baseline": 800, "optimized": 1000, "higher_is_better": True}) == 1.25 # throughput up
|
| 29 |
+
assert speedup({"baseline": None, "optimized": None, "stated_speedup": 1.3}) == 1.3
|
| 30 |
+
ms = [{"scope": "kernel", "batch_size": 8, "hardware": "H200", "speedup": 1.2},
|
| 31 |
+
{"scope": "kernel", "batch_size": 8, "hardware": "H20", "speedup": 1.5}]
|
| 32 |
+
assert gain_at(ms, 8, "NVIDIA_H20", {}, n_files=2) == 1.5 # multi-file PR: GPU must match
|
| 33 |
+
assert gain_at(ms, 8, "NVIDIA_H20", {}, n_files=1) is None # 1.2 vs 1.5 disagree -> ambiguous
|
| 34 |
+
assert gain_at(ms, 16, "NVIDIA_H20", {}, n_files=1) is None
|
| 35 |
+
shaped = [{"scope": "kernel", "batch_size": 8, "shape": "N=7168,K=2048", "speedup": 1.1},
|
| 36 |
+
{"scope": "kernel", "batch_size": 8, "shape": "N=4096,K=2048", "speedup": 2.0}]
|
| 37 |
+
assert gain_at(shaped, 8, "NVIDIA_H20", {"N": "7168", "K": "2048"}, n_files=1) == 1.1 # shape disambiguates
|
| 38 |
+
|
| 39 |
+
from gains import CHUNK, chunks
|
| 40 |
+
table = "| M | before | after |\n|---|---|---|\n" + "\n".join(f"| {i} | 10 | 5 |" for i in range(1000))
|
| 41 |
+
parts = chunks("intro\n\n" + table)
|
| 42 |
+
assert len(parts) > 1 and all(len(p) <= CHUNK + 200 for p in parts)
|
| 43 |
+
assert all("| M | before | after |" in p for p in parts[1:]) # header repeated on every table piece
|
| 44 |
+
assert sum(p.count("| 10 | 5 |") for p in parts) == 1000 # no rows lost or duplicated
|
| 45 |
+
assert chunks("short body") == ["short body\n\n"]
|
| 46 |
+
|
| 47 |
+
from build import file_license, permissive
|
| 48 |
+
assert file_license("// SPDX-License-Identifier: Apache-2.0\nint x;") == "Apache-2.0"
|
| 49 |
+
assert file_license("/* SPDX-License-Identifier: BSD-3-Clause */") == "BSD-3-Clause"
|
| 50 |
+
assert file_license("int x; // no header") == "Apache-2.0"
|
| 51 |
+
assert not permissive(file_license("// SPDX-License-Identifier: NVIDIA TensorRT Source Code License Agreement"))
|
| 52 |
+
assert not permissive(file_license("NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights"))
|
| 53 |
+
|
| 54 |
+
from reward import patch_reward
|
| 55 |
+
before, after = "a\nb = slow(x)\nc\n", "a\nb = fast(x)\nc\n"
|
| 56 |
+
ok = "<<<<<<< SEARCH\nb = slow(x)\n=======\nb = fast(x)\n>>>>>>> REPLACE"
|
| 57 |
+
assert patch_reward(ok, before, after) == 1.0
|
| 58 |
+
assert patch_reward(ok.replace("slow", "missing"), before, after) == -1.0 # SEARCH not in file
|
| 59 |
+
assert patch_reward("just rewrite it", before, after) == -1.0
|
| 60 |
+
assert 0 <= patch_reward(ok.replace("fast(x)", "faster(y)"), before, after) < 1
|
| 61 |
+
print("ok")
|
code/uv.lock
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|