File size: 22,898 Bytes
e58c676
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbc46f5
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
"""Build a kernel-optimization RL dataset from vLLM / SGLang / FlashInfer source and git history.

Subsets:
  tuned_configs  - (Triton kernel source, model shape, GPU, batch size) -> autotuned launch config.
  kernel_commits - before/after kernel code from performance commits, tagged with model + hardware.

Usage: uv run build.py [--push REPO_ID] [--from-disk]
"""

import ast
import difflib
import functools
import hashlib
import json
import re
import statistics
import subprocess
import sys
from pathlib import Path

from datasets import Dataset, DatasetDict, load_from_disk
from huggingface_hub import HfApi, hf_hub_download

import gains

ROOT = Path(__file__).parent
REPOS = ROOT / ".context/repos"
OUT = ROOT / ".context/out"
GITHUB = {"vllm": "vllm-project/vllm", "sglang": "sgl-project/sglang", "flashinfer": "flashinfer-ai/flashinfer"}


# --------------------------------------------------------------------------- git helpers
def git(repo: str, *args: str) -> str:
    return subprocess.run(["git", "-C", str(REPOS / repo), *args], capture_output=True, check=True).stdout.decode(
        "utf-8", "replace"
    )


def ensure_clone(repo: str) -> None:
    # Blobless clone: full history (commits+trees) but file contents are fetched on demand.
    if not (REPOS / repo).exists():
        REPOS.mkdir(parents=True, exist_ok=True)
        subprocess.run(
            ["git", "clone", "-q", "--filter=blob:none", "--no-checkout", f"https://github.com/{GITHUB[repo]}", str(REPOS / repo)],
            check=True,
        )


def fetch_blobs(repo: str, oids: list[str]) -> None:
    # One round trip per 2k blobs instead of git's lazy one-blob-per-request fetch.
    oids = sorted(set(oids))
    for i in range(0, len(oids), 2000):
        git(repo, "-c", "fetch.negotiationAlgorithm=noop", "fetch", "-q", "--no-tags", "--no-write-fetch-head",
            "--filter=blob:none", "origin", *oids[i : i + 2000])


def blob(repo: str, oid: str) -> str:
    return git(repo, "cat-file", "-p", oid)


def ls_tree(repo: str, prefix: str) -> list[tuple[str, str]]:
    """(oid, path) for every file under prefix at HEAD."""
    rows = [line.split(None, 3) for line in git(repo, "ls-tree", "-r", "HEAD", "--", prefix).splitlines()]
    return [(r[2], r[3]) for r in rows if r[1] == "blob"]


LICENSE_RE = re.compile(r"SPDX-License-Identifier:\s*([^\n*]+)|(proprietary rights|TensorRT Source Code License)"
                        r"|(Apache License)|(Redistribution and use in source and binary forms)|(Permission is hereby granted)", re.I)


def file_license(code: str) -> str:
    """License declared in the file header; header-less files inherit their repo's Apache-2.0."""
    m = LICENSE_RE.search(code[:5000])
    if not m:
        return "Apache-2.0"
    spdx, proprietary, apache, bsd, mit = m.groups()
    return spdx.strip() if spdx else "proprietary" if proprietary else "Apache-2.0" if apache else "BSD" if bsd else "MIT"


def permissive(lic: str) -> bool:
    return lic.startswith(("Apache-2.0", "BSD", "MIT"))


@functools.cache
def head_license(repo: str, path: str) -> str:
    return file_license(git(repo, "show", f"HEAD:{path}"))


def stage_licenses() -> Path:
    """Upstream LICENSE/NOTICE files: Apache-2.0 sec. 4 requires shipping them with redistributed code."""
    for repo in GITHUB:
        files = [(o, p) for o, p in ls_tree(repo, ".") if re.match(r"(LICENSE|NOTICE|licenses/)", p)]
        fetch_blobs(repo, [o for o, _ in files])
        for oid, p in files:
            dst = OUT / "licenses" / repo / p
            dst.parent.mkdir(parents=True, exist_ok=True)
            dst.write_text(blob(repo, oid))
    return OUT / "licenses"


# --------------------------------------------------------------------------- subset 1: tuned configs
CONFIG_DIRS = [
    ("vllm", "vllm/model_executor/layers/fused_moe/configs/"),
    ("vllm", "vllm/model_executor/layers/quantization/utils/configs/"),
    ("vllm", "vllm/model_executor/layers/mamba/ops/configs/selective_state_update/"),
    ("sglang", "python/sglang/srt/layers/moe/moe_runner/triton_utils/configs/"),
    ("sglang", "python/sglang/kernels/ops/gemm/configs/"),
]


def pick_kernel(repo: str, cfg_dir: str, dtype: str, block_shape: str | None) -> tuple[str, str] | None:
    """Mirror each repo's runtime dispatch: (file, @triton.jit fn) that consumes this config, or None."""
    if "moe" in cfg_dir:
        f = {"vllm": "vllm/model_executor/layers/fused_moe/fused_moe.py",
             "sglang": "python/sglang/kernels/ops/moe/fused_moe_triton_kernels.py"}[repo]
        return f, "fused_moe_kernel_gptq_awq" if dtype.startswith("int4_w4a16") else "fused_moe_kernel"
    if "mamba" in cfg_dir:
        return "vllm/model_executor/layers/mamba/ops/mamba_ssm.py", "_selective_scan_update_kernel"
    if not block_shape:  # channelwise / bf16 GEMM configs feed other kernels
        return None
    if repo == "vllm":  # vllm's int8 block configs are orphaned (kernel removed upstream)
        return ("vllm/model_executor/layers/quantization/utils/fp8_utils.py", "_w8a8_triton_block_scaled_mm") \
            if dtype.startswith("fp8") else None
    if dtype.startswith("int8"):
        return "python/sglang/kernels/ops/gemm/int8_kernel.py", "_w8a8_block_int8_matmul"
    if dtype.startswith("fp8"):
        return "python/sglang/kernels/ops/gemm/fp8_kernel.py", "_w8a8_block_fp8_matmul"
    return None
# ponytail: hand-picked MoE models for shape->model matching; add repo ids here to widen coverage.
MOE_MODELS = [
    "mistralai/Mixtral-8x7B-v0.1", "mistralai/Mixtral-8x22B-v0.1", "deepseek-ai/DeepSeek-V2-Lite",
    "deepseek-ai/DeepSeek-V2", "deepseek-ai/DeepSeek-V3", "moonshotai/Kimi-K2-Instruct", "Qwen/Qwen1.5-MoE-A2.7B",
    "Qwen/Qwen2-57B-A14B", "Qwen/Qwen3-30B-A3B", "Qwen/Qwen3-235B-A22B", "Qwen/Qwen3-Coder-480B-A35B-Instruct",
    "Qwen/Qwen3-Next-80B-A3B-Instruct", "openai/gpt-oss-20b", "openai/gpt-oss-120b",
    "meta-llama/Llama-4-Scout-17B-16E-Instruct", "meta-llama/Llama-4-Maverick-17B-128E-Instruct",
    "databricks/dbrx-instruct", "allenai/OLMoE-1B-7B-0924", "ai21labs/AI21-Jamba-Mini-1.5", "zai-org/GLM-4.5",
    "zai-org/GLM-4.5-Air", "zai-org/GLM-4.6", "MiniMaxAI/MiniMax-M2", "microsoft/Phi-3.5-MoE-instruct",
    "baidu/ERNIE-4.5-21B-A3B-PT", "baidu/ERNIE-4.5-300B-A47B-PT", "tencent/Hunyuan-A13B-Instruct",
    "ibm-granite/granite-3.1-3b-a800m-instruct", "deepseek-ai/deepseek-moe-16b-base", "jetmoe/jetmoe-8b",
    "meituan-longcat/LongCat-Flash-Chat", "inclusionAI/Ling-lite-1.5", "XiaomiMiMo/MiMo-V2-Flash",
]
EXPERT_KEYS = ["num_local_experts", "n_routed_experts", "num_experts", "moe_num_experts"]
INTER_KEYS = ["moe_intermediate_size", "expert_ffn_hidden_size", "intermediate_size", "ffn_hidden_size"]


def moe_shapes() -> dict[str, tuple[int, int]]:
    """model -> (num_experts, per-expert intermediate size), cached on disk."""
    cache = OUT / "moe_models.json"
    if cache.exists():
        return {k: tuple(v) for k, v in json.loads(cache.read_text()).items()}

    shapes = {}
    for rid in MOE_MODELS:
        try:
            cfg = json.loads(Path(hf_hub_download(rid, "config.json")).read_text())
        except Exception as e:  # gated / renamed repos are just skipped
            print(f"  skip {rid}: {type(e).__name__}", file=sys.stderr)
            continue
        cfg = cfg.get("text_config") or cfg.get("ffn_config", {}) | cfg
        e = next((cfg[k] for k in EXPERT_KEYS if isinstance(cfg.get(k), int)), None)
        n = next((cfg[k] for k in INTER_KEYS if isinstance(cfg.get(k), int)), None)
        if e and n:
            shapes[rid.split("/")[1]] = (e, n)
    cache.write_text(json.dumps(shapes, indent=1))
    return shapes


def match_models(E: int, N: int, shapes: dict) -> list[str]:
    """Models whose MoE layer yields this (E, N) under tensor parallel (N=I/tp) or expert parallel (E=experts/ep)."""
    out = []
    for name, (experts, inter) in shapes.items():
        out += [f"{name} (TP{tp})" for tp in (1, 2, 4, 8, 16) if E == experts and N * tp == inter]
        out += [f"{name} (EP{ep})" for ep in (2, 4, 8, 16, 32) if N == inter and E * ep == experts]
    return out


def parse_config_name(name: str) -> dict:
    """'E=8,N=14336,device_name=NVIDIA_H100,block_shape=[128, 128].json' -> dict."""
    return {k: v for k, v in re.findall(r"(\w+)=(\[[^\]]*\]|[^,]+)", name.removesuffix(".json"))}


@functools.cache
def kernel_source(repo: str, path: str, fn: str) -> str | None:
    code = git(repo, "show", f"HEAD:{path}")
    for node in ast.walk(ast.parse(code)):
        if isinstance(node, ast.FunctionDef) and node.name == fn:
            start = min([d.lineno for d in node.decorator_list] + [node.lineno])
            return "\n".join(code.splitlines()[start - 1 : node.end_lineno])
    return None


def config_prompt(r: dict) -> str:
    spec = "\n".join(f"- {k}: {v}" for k, v in r["shape"].items())
    models = ", ".join(r["candidate_models"]) or "unknown"
    return (
        f"You are tuning the Triton kernel `{r['kernel_name']}` (from {r['repo']}) for one deployment.\n\n"
        f"Hardware: {r['device_name']}\nQuant dtype: {r['dtype']}\nProblem shape:\n{spec}\n"
        f"Batch size (tokens, M): {r['M']}\nModels with this shape: {models}\n\n"
        f"Kernel source:\n```python\n{r['kernel_source']}\n```\n\n"
        f"Pick the fastest launch configuration. Answer with a JSON object with exactly these keys: "
        f"{', '.join(json.loads(r['best_config']))}."
    )


def config_prs(repo: str, prefix: str) -> dict[str, tuple[int | None, int]]:
    """config path -> (PR of the newest commit that added/changed it, #config files that commit touched)."""
    log = git(repo, "log", "--no-renames", "--diff-filter=AM", "--format=%x00%s", "--name-only", "--", prefix)
    out = {}
    for chunk in log.split("\x00")[1:]:
        subject, *paths = [l for l in chunk.splitlines() if l]
        pr = re.search(r"\(#(\d+)\)\s*$", subject)
        for p in paths:
            out.setdefault(p, (int(pr[1]) if pr else None, len(paths)))
    return out


def same_gpu(hw: str | None, device: str) -> bool:
    """Token match: 'H100' ~ 'NVIDIA_H100_80GB_HBM3', but 'H20' never matches 'NVIDIA_H200'."""
    toks = lambda s: set(re.split(r"[^A-Z0-9]+", s.upper())) - {"", "NVIDIA", "AMD", "INSTINCT"}
    return bool(hw) and toks(hw) <= toks(device)


def shape_ok(shape: str | None, meta: dict) -> bool:
    """No key=value in the measurement's shape contradicts the config's own (E, N, K, headdim, ...)."""
    got = {k.lower(): v for k, v in re.findall(r"(\w+)\s*=\s*([^,;\s]+)", shape or "")}
    return all(got[k.lower()] == str(v) for k, v in meta.items() if k.lower() in got)


def gain_at(ms: list[dict], M: int, device: str, meta: dict, n_files: int) -> float | None:
    """Documented kernel speedup of the tuned config over the default at batch size M, only when unambiguous."""
    c = [m for m in ms if m.get("scope") == "kernel" and m.get("batch_size") == M and shape_ok(m.get("shape"), meta)]
    if n_files > 1:  # PR tuned several files: only trust rows that name this GPU
        c = [m for m in c if same_gpu(m.get("hardware"), device)]
    s = [m["speedup"] for m in c]
    # rows that disagree (e.g. per-dtype tables the extractor didn't label) -> don't guess
    return round(statistics.median(s), 4) if s and max(s) / min(s) <= 1.05 else None


def build_tuned_configs() -> list[dict]:
    shapes = moe_shapes()
    print(f"  {len(shapes)} MoE model shapes", file=sys.stderr)
    rows = []
    for repo, prefix in CONFIG_DIRS:
        files = [(o, p) for o, p in ls_tree(repo, prefix) if p.endswith(".json")]
        fetch_blobs(repo, [o for o, _ in files])
        sha = git(repo, "rev-parse", "HEAD").strip()
        prs = config_prs(repo, prefix)
        for oid, path in files:
            pr, n_files = prs.get(path, (None, 0))
            meta = parse_config_name(Path(path).name)
            dtype = meta.pop("dtype", "bf16/fp16")
            device = meta.pop("device_name", None)
            block_shape = meta.pop("block_shape", None)
            kernel = pick_kernel(repo, prefix, dtype, block_shape)
            src = kernel and kernel_source(repo, *kernel)
            if not device or not src:
                print(f"  skip {path}: no device or kernel {kernel}", file=sys.stderr)
                continue
            kfile, kfn = kernel
            if not permissive(head_license(repo, kfile)):
                continue
            table = json.loads(blob(repo, oid))
            triton_dir = re.search(r"triton_(\d+_\d+_\d+)", path)
            triton_ver = table.pop("triton_version", None) or (triton_dir and triton_dir[1].replace("_", "."))
            E, N = meta.get("E"), meta.get("N")
            cands = match_models(int(E), int(N), shapes) if E and N and "fused_moe" in kfn else []
            for M, cfg in table.items():
                if not M.isdigit() or not isinstance(cfg, dict):
                    continue
                r = dict(
                    repo=repo, commit=sha, config_path=path, kernel_file=kfile, kernel_name=kfn,
                    kernel_source=src, license=head_license(repo, kfile), device_name=device, dtype=dtype, block_shape=block_shape,
                    triton_version=triton_ver, shape=meta, M=int(M), candidate_models=cands,
                    best_config=json.dumps(cfg), config_pr=pr, config_pr_files=n_files,
                    # group by basename so the same shape (any repo / triton version / M) never straddles splits
                    split="test" if int(hashlib.md5(Path(path).name.encode()).hexdigest(), 16) % 10 == 0 else "train",
                )
                r["prompt"] = config_prompt(r)
                r["shape"] = json.dumps(meta)
                rows.append(r)
        print(f"  {repo}:{prefix} -> {len(rows)} rows so far", file=sys.stderr)
    docs = gains.fetch_all({(GITHUB[r["repo"]], r["config_pr"]): Path(r["config_path"]).name for r in rows if r["config_pr"]})
    for r in rows:
        pr, n_files = r.pop("config_pr"), r.pop("config_pr_files")
        ms = docs[(GITHUB[r["repo"]], pr)][1] if pr else []
        r["config_pr_url"] = f"https://github.com/{GITHUB[r['repo']]}/pull/{pr}" if pr else None
        r["config_pr_gains"] = json.dumps(ms)
        r["speedup_vs_default"] = gain_at(ms, r["M"], r["device_name"], json.loads(r["shape"]), n_files)
    return rows


# --------------------------------------------------------------------------- subset 2: kernel commits
KERNEL_PATHS = {
    "vllm": ["csrc", "vllm/model_executor/layers", "vllm/attention", "vllm/v1/attention", "vllm/kernels"],
    "sglang": ["sgl-kernel", "python/sglang/srt/layers", "python/sglang/kernels"],
    "flashinfer": ["include", "csrc", "flashinfer"],
}
PERF_GREP = r"\[perf\]|optimi|speed ?up|faster|perf|tune|tuning|accelerat|throughput|latency"
PERF_TITLE = re.compile(PERF_GREP, re.I)  # git --grep also hits PR bodies; require the signal in the title
SKIP_TITLE = re.compile(r"^revert|\[(build|ci|ci/build|doc|docs|test|tests|misc)\]|compil|\bjit\b|wheel|\bci\b", re.I)
SKIP_PATH = re.compile(r"(^|/)(tests?|benchmarks?|docs?|examples?|configs?)/")
LANG = {".cu": "cuda", ".cuh": "cuda", ".cpp": "cpp", ".cc": "cpp", ".h": "cpp", ".hpp": "cpp", ".py": "python"}
MAX_FILES_PER_COMMIT, MAX_BYTES, MAX_CHANGED = 10, 120_000, 800
FAMILIES = {
    "deepseek": r"deep ?seek|\bdsv\d|\bds-?v\d|\bds-?r1\b", "qwen": r"qwen", "llama": r"llama", "mixtral": r"mixtral",
    "mistral": r"mistral|ministral", "kimi": r"kimi|moonshot", "glm": r"\bglm", "gpt-oss": r"gpt-?oss",
    "gemma": r"gemma", "minimax": r"minimax", "mamba": r"mamba|nemotron-?h\b", "nemotron": r"nemotron",
    "phi": r"\bphi-?\d", "grok": r"grok", "ernie": r"ernie", "hunyuan": r"hunyuan", "jamba": r"jamba",
    "dbrx": r"dbrx", "olmo": r"olmo", "granite": r"granite", "llava/vlm": r"llava|\bvlm\b|\bvision\b",
}
HW_RE = re.compile(
    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?"
    r"|hopper|blackwell|ampere|ada|rocm|xpu|npu|cpu|tpu|gaudi)\b", re.I)
SPEEDUP_RE = re.compile(r"\b\d+(?:\.\d+)?\s?[x×](?![\w\d])")


def kernel_lang(path: str, code: str) -> str | None:
    lang = LANG.get(Path(path).suffix)
    if lang != "python":
        return lang
    if "@triton.jit" in code or "@triton.autotune" in code:
        return "triton"
    if "cutlass.cute" in code or "@cute.kernel" in code:
        return "cute_dsl"
    return None  # plain Python glue isn't a kernel


def tags(text: str) -> tuple[list[str], list[str], list[str]]:
    low = text.lower()
    models = [f for f, rx in FAMILIES.items() if re.search(rx, low)]
    hw = sorted({re.sub(r"^(SM\d+)A$", r"\1", re.sub(r"[ _]", "", h.upper())) for h in HW_RE.findall(text)})
    return models, hw, SPEEDUP_RE.findall(text)[:10]


def perf_commits(repo: str) -> list[dict]:
    log = git(repo, "log", "--no-merges", "--no-renames", "-i", "-E", f"--grep={PERF_GREP}",
              "--format=%x00%H%x1f%aI%x1f%B%x1e", "--raw", "--no-abbrev", "--", *KERNEL_PATHS[repo])
    commits = []
    for chunk in log.split("\x00")[1:]:
        head, raw = chunk.split("\x1e", 1)
        sha, date, msg = head.split("\x1f", 2)
        title = msg.strip().splitlines()[0]
        if not PERF_TITLE.search(title) or SKIP_TITLE.search(title):
            continue
        files = []
        for line in raw.strip().splitlines():
            meta, path = line.split("\t", 1)
            _, _, old, new, status = meta.split()
            if status == "M" and Path(path).suffix in LANG and not SKIP_PATH.search(path):
                files.append((path, old, new))
        if 0 < len(files) <= MAX_FILES_PER_COMMIT:
            commits.append(dict(sha=sha, date=date, msg=msg.strip(), files=files))
    return commits


EDIT_FORMAT = """Respond with one or more edits to the file, each in exactly this format:
<<<<<<< SEARCH
(exact, contiguous lines copied from the current file)
=======
(the replacement lines)
>>>>>>> REPLACE"""
FENCE = {"cuda": "cuda", "cpp": "cpp", "triton": "python", "cute_dsl": "python"}


def commit_prompt(r: dict) -> str:
    # the PR title is the task statement (like the issue in SWE-RL); the PR body is withheld since it describes the fix
    goal = re.sub(r"\s*\(#\d+\)\s*$", "", r["title"])
    return (
        f"Optimize this {r['language']} kernel file from {r['repo']} ({r['path']}).\n\n"
        f"Goal: {goal}\nTarget hardware: {', '.join(r['hardware_mentioned']) or 'unspecified'}\n"
        f"Target models: {', '.join(r['models_mentioned']) or 'unspecified'}\n\n"
        f"Current file:\n```{FENCE[r['language']]}\n{r['before_code']}\n```\n\n{EDIT_FORMAT}"
    )


def build_kernel_commits() -> list[dict]:
    rows = []
    for repo in KERNEL_PATHS:
        commits = perf_commits(repo)
        fetch_blobs(repo, [o for c in commits for _, a, b in c["files"] for o in (a, b)])
        for c in commits:
            title = c["msg"].splitlines()[0]
            pr = re.search(r"\(#(\d+)\)", title)
            for path, old, new in c["files"]:
                before, after = blob(repo, old), blob(repo, new)
                lang = kernel_lang(path, after)
                lic = file_license(after)
                if not lang or max(len(before), len(after)) > MAX_BYTES or not (permissive(lic) and permissive(file_license(before))):
                    continue
                diff = list(difflib.unified_diff(before.splitlines(), after.splitlines(), path, path, lineterm=""))
                added = sum(1 for l in diff if l.startswith("+") and not l.startswith("+++"))
                removed = sum(1 for l in diff if l.startswith("-") and not l.startswith("---"))
                if not 0 < added + removed <= MAX_CHANGED:
                    continue
                models, hw, speedups = tags(c["msg"] + "\n" + path)
                rows.append(dict(
                    repo=repo, commit=c["sha"], date=c["date"], pr_number=int(pr[1]) if pr else None,
                    pr_url=f"https://github.com/{GITHUB[repo]}/pull/{pr[1]}" if pr else None,
                    title=title, message=c["msg"][:8000], path=path, language=lang, license=lic,
                    before_code=before, after_code=after, diff="\n".join(diff),
                    lines_added=added, lines_removed=removed, files_in_commit=len(c["files"]),
                    models_mentioned=models, hardware_mentioned=hw, speedup_claims=speedups,
                ))
                rows[-1]["prompt"] = commit_prompt(rows[-1])
        print(f"  {repo}: {len(commits)} commits -> {len(rows)} rows so far", file=sys.stderr)
    docs = gains.fetch_all({(GITHUB[r["repo"]], r["pr_number"]): r["title"] for r in rows if r["pr_number"]})
    for r in rows:
        body, ms = docs[(GITHUB[r["repo"]], r["pr_number"])] if r["pr_number"] else ("", [])
        r |= dict(pr_body=body[:gains.MAX_BODY], gains=json.dumps(ms),
                  kernel_speedup=gains.summarize(ms, "kernel"), e2e_speedup=gains.summarize(ms, "e2e"))
    # temporal split: newest ~10% of commits is test (closest to post-training-cutoff code)
    cutoff = sorted(r["date"] for r in rows)[int(len(rows) * 0.9)]
    for r in rows:
        r["split"] = "test" if r["date"] >= cutoff else "train"
    return rows


# --------------------------------------------------------------------------- main
def to_dd(rows: list[dict]) -> DatasetDict:
    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])
                        for s in ("train", "test")})


if __name__ == "__main__":
    OUT.mkdir(parents=True, exist_ok=True)
    for repo in GITHUB:
        ensure_clone(repo)
    if "--from-disk" in sys.argv:  # push the last build (e.g. after editing only the card)
        subsets = {name: load_from_disk(OUT / name) for name in ("tuned_configs", "kernel_commits")}
    else:
        subsets = {"tuned_configs": to_dd(build_tuned_configs()), "kernel_commits": to_dd(build_kernel_commits())}
        for name, dd in subsets.items():
            print(name, dd, file=sys.stderr)
            dd.save_to_disk(OUT / name)
    if "--push" in sys.argv:
        repo_id = sys.argv[sys.argv.index("--push") + 1]
        for name, dd in subsets.items():
            dd.push_to_hub(repo_id, config_name=name)
        HfApi().upload_folder(folder_path=stage_licenses(), path_in_repo="licenses", repo_id=repo_id, repo_type="dataset")
        HfApi().upload_folder(folder_path=ROOT, path_in_repo="code", repo_id=repo_id, repo_type="dataset",
                              allow_patterns=["build.py", "gains.py", "reward.py", "test_build.py", "pyproject.toml", "uv.lock"])
        # our card carries the `configs:` YAML, so it replaces the auto-generated one
        HfApi().upload_file(path_or_fileobj=ROOT / "README.md", path_in_repo="README.md", repo_id=repo_id, repo_type="dataset")