File size: 40,448 Bytes
5d12def
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
"""Bounded code/feedback trials: local model gateway, remote GPU grader, NAS archive."""

import argparse
import ast
from concurrent.futures import ThreadPoolExecutor, as_completed
import datetime as dt
import hashlib
from itertools import count
import json
import math
import os
from pathlib import Path
import re
import secrets
import shlex
import shutil
import subprocess
import tempfile
import threading
import time
import urllib.error
import urllib.request
import zipfile

from .metrics import geometric_mean
from . import LEGACY_PROTOCOL
from . import main_h100, kernel_v07, kernel_v08, kernel_v081


ROOT = Path(__file__).resolve().parent.parent
SCAFFOLD = "code-feedback-v1.10"
SYSTEM = """You are optimizing a GPU inference kernel. Return exactly one fenced python
code block containing the complete submission.py. The controller executes your code
on public workloads and returns correctness/performance feedback for revisions.
Only the public task pack and that feedback are available. Do not import kernel_bench,
read grader files, inspect callers, change global precision/checking/timing state,
access files/network/processes, or cache input-dependent outputs. Installed PyTorch,
Triton and CUDA libraries and metadata-specialized compilation are allowed. Write a
self-contained implementation, including any helper kernels. Honor the exact function
signature. Optimize all workload regimes, not only the smallest case. Compilation
is outside timing; CUDA Graph capture is required. Do not use tensor.item() on CUDA
data or other host synchronization inside the function. Hidden inputs are fresh.
Your latest answer is your final deliverable when the budget expires. Each revision
replaces the previous answer. Return a complete file every time. To finish early,
place FINAL on its own line immediately before the single fenced code block.
The controller freezes that answer. An invalid final answer receives zero.
Hidden evaluation is performed only after freezing and is never returned to you.
"""


def save(path, value):
    path.parent.mkdir(parents=True, exist_ok=True)
    tmp = path.with_suffix(path.suffix + ".tmp")
    tmp.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n")
    tmp.replace(path)


def digest(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()


def utc():
    return dt.datetime.now(dt.timezone.utc).isoformat()


def extract_code(content, task):
    blocks = re.findall(r"```(?:python|py)?\s*\n(.*?)```", content or "", re.S)
    if len(blocks) != 1:
        raise ValueError("Expected exactly one fenced Python code block")
    code = blocks[0].strip() + "\n"
    tree = ast.parse(code)
    signatures = kernel_v07.SIGNATURES.get(task, [task])
    required = {s.split("(")[0] for s in signatures}
    defined = {n.name for n in tree.body if isinstance(n, ast.FunctionDef)}
    if required - defined:
        raise ValueError("Missing top-level function(s): " + ", ".join(sorted(required - defined)))
    # This is a protocol check, not a security sandbox.
    for n in ast.walk(tree):
        names = [a.name for a in n.names] if isinstance(n, ast.Import) else []
        if isinstance(n, ast.ImportFrom):
            names.append(n.module or "")
        if any(s == "kernel_bench" or s.startswith("kernel_bench.") for s in names):
            raise ValueError("Importing benchmark implementation is forbidden")
    return code


def feedback(result):
    rows = []
    for row in result.get("cases", []):
        item = {k: row[k] for k in ("id", "status", "error", "reason", "exit_code", "allocation_profile") if k in row}
        if "error" in item:
            message = item["error"]
            if len(message) > 8000:
                item["error"] = message[:3960] + "\n[long diagnostic shortened]\n" + message[-3960:]
        if "phase_errors" in row:
            item["phase_errors"] = {phase: message[:4800] for phase, message in row["phase_errors"].items()}
        for phase in ("forward", "backward", "kernel", "block"):
            if phase in row:
                item[phase] = {k: row[phase][k] for k in
                               ("baseline_us", "candidate_us", "speedup", "speedup_ci95",
                                "baseline_cv", "candidate_cv", "memory", "native_api_reused") if k in row[phase]}
        rows.append(item)
    payload = {"cases": rows, "summary": result.get("summary", {})}
    if result.get("warnings"):
        payload["warnings"] = result["warnings"]
    return payload


def rank(result):
    passed = [r for r in result.get("cases", []) if r.get("status") == "passed"]
    speed = geometric_mean([r["kernel"]["speedup"] for r in passed]) if passed else 0
    return len(passed), speed


def baseline_errors(result, private=False):
    return [{"id": row["id"], "error": "Hidden baseline or hardware control failed" if private else row["error"]}
            for row in result.get("cases", [])
            if row.get("status") == "error" and
            row.get("error", "").startswith("RuntimeError: Baseline failed ")]


def model_payload(config, messages):
    if config.get("api", "chat_completions") == "responses":
        # Replay visible code and public feedback only, matching the chat scaffold.
        # Responses has no sampling-seed field; config.seed still fixes public GPU inputs.
        return {"model": config["model"], "input": messages, "store": False,
                "max_output_tokens": config["max_output_tokens"],
                "temperature": config["temperature"],
                "reasoning": {"effort": config["reasoning_effort"]}}
    return {"model": config["model"], "messages": messages, "seed": config["seed"],
            "max_tokens": config["max_output_tokens"], "temperature": config["temperature"],
            "reasoning_effort": config["reasoning_effort"]}


def normalize_response(raw, api):
    if api != "responses":
        if not raw.get("choices"):
            raise ValueError("Gateway response has no choices")
        return raw
    if raw.get("status") not in ("completed", "incomplete"):
        raise ValueError("Responses request did not complete: " + str(raw.get("status")))
    history = []
    for item in raw.get("output", []):
        if (item.get("type") == "message" and item.get("role") == "assistant"
                and item.get("phase") in (None, "final_answer")):
            message = {"role": "assistant", "content": "\n".join(
                part["text"] for part in item.get("content", []) if part.get("type") == "output_text")}
            if item.get("phase") is not None:
                message["phase"] = item["phase"]
            history.append(message)
    text = "\n".join(message["content"] for message in history)
    usage = raw.get("usage")
    finish = "stop" if raw["status"] == "completed" else (raw.get("incomplete_details") or {}).get("reason", "incomplete")
    return {"id": raw.get("id"), "model": raw.get("model"), "assistant_history": history,
            "system_fingerprint": raw.get("system_fingerprint"),
            "choices": [{"finish_reason": "length" if finish == "max_output_tokens" else finish,
                         "message": {"role": "assistant", "content": text}}],
            "usage": None if usage is None else {"prompt_tokens": usage["input_tokens"],
                "completion_tokens": usage["output_tokens"], "total_tokens": usage["total_tokens"],
                "completion_tokens_details": usage.get("output_tokens_details")}}


def public_prompt(pack, config):
    metadata = json.loads((pack / "task.json").read_text())
    cases = json.loads((pack / "public_cases.json").read_text())["cases"]
    names = ["TASK.md", "contracts.md", "public_cases.json", "submission.py"]
    names += [name for name in ("marlin-layout.md", "marlin_layout.py", "Apache-2.0.txt")
              if (pack / name).is_file()]
    prompt = "\n\n".join(f"## {name}\n{(pack/name).read_text()}" for name in names)
    if "numerical_contract" in metadata:
        prompt += "\n\n## Exact numerical acceptance\n" + json.dumps(metadata["numerical_contract"])
    hardware = metadata.get("hardware", "NVIDIA H100 80GB HBM3")
    runtime = ("pinned DeepGEMM 5081f851 and NCCL" if metadata.get("id") == kernel_v07.MOE else
               "PyTorch 2.9.1+cu128, Triton 3.5.1, Python 3.11")
    limit = config.get("turns")
    if limit is not None:
        budget = f"{limit} model submissions"
    elif config.get("public_evaluation_seconds") is None:
        budget = (f"no submission-count limit within {config['wall_seconds']} seconds total "
                  "for model calls, revisions and public GPU evaluation")
    else:
        budget = (f"no submission-count limit within {config['wall_seconds']} seconds of development "
                  f"and {config['public_evaluation_seconds']} seconds of public evaluation")
    prompt += (f"\nEnvironment: {hardware}, {runtime}. "
               f"Budget: {budget}; each is evaluated on all {len(cases)} public cases. "
               f"Each response has at most {config['max_output_tokens']} tokens including reasoning. "
               "Guaranteed libraries: " + config.get("installed_libraries", "torch, triton, Python standard library") + ". "
               "Copy any needed public helper code into your single submission file. "
               "Preserve exact numerical boundaries; optimize all workload regimes.")
    return prompt, len(cases)


def prepare_private(root, run, tasks, version, reference=None):
    private = Path(root) / "kernel_bench/private" / version
    target = private / run
    target.mkdir(parents=True, mode=0o700)
    if reference is not None:
        # Paired model comparisons reuse an already sealed split, never model feedback.
        source_run = reference["run"]
        if Path(source_run).name != source_run or source_run in (".", ".."):
            raise ValueError("Private reference must be a run basename")
        counts, hashes = {}, {}
        for task in tasks:
            source = private / source_run / task / "suite.json"
            if digest(source) != reference["suite_sha256"][task]:
                raise ValueError("Private reference hash mismatch: " + task)
            data = json.loads(source.read_text())
            if version == kernel_v081.PACK:
                if data.get("protocol_version") != kernel_v081.VERSION:
                    raise ValueError("Private suite version differs from the v0.8.1 baseline revision")
                kernel_v081.validate(data)
            if not data["cases"] or any(c["task"] != task for c in data["cases"]):
                raise ValueError("Private reference task mismatch: " + task)
            directory = target / task
            directory.mkdir(mode=0o700)
            path = directory / "suite.json"
            shutil.copyfile(source, path)
            path.chmod(0o600)
            counts[task], hashes[task] = len(data["cases"]), digest(path)
        return {"hidden_case_counts": counts, "hidden_suite_sha256": hashes}
    if version in ("v0.5-h100-kernels", main_h100.PACK, kernel_v07.PACK, kernel_v08.PACK, kernel_v08.DIAGNOSTIC_PACK, kernel_v081.PACK):
        from .build_expansion_suites import suite
        if version == main_h100.PACK:
            suite = main_h100.suite
        elif version == kernel_v07.PACK:
            suite = kernel_v07.suite
        elif version in (kernel_v08.PACK, kernel_v08.DIAGNOSTIC_PACK):
            suite = kernel_v08.suite
        elif version == kernel_v081.PACK:
            suite = kernel_v081.suite
        options = {"diagnostic": True} if version == kernel_v08.DIAGNOSTIC_PACK else {}
        data = suite(seed=secrets.randbits(48), private=True, **options)
        data["input_seed"] = secrets.randbits(48)
    else:
        data = json.loads((private / "holdout.json").read_text())
    counts, hashes = {}, {}
    for task in tasks:
        subset = {**data, "cases": [c for c in data["cases"] if c["task"] == task]}
        if not subset["cases"]:
            raise ValueError("Missing private cases for " + task)
        directory = target / task
        directory.mkdir(mode=0o700)
        path = directory / "suite.json"
        save(path, subset)
        path.chmod(0o600)
        counts[task], hashes[task] = len(subset["cases"]), digest(path)
    return {"hidden_case_counts": counts, "hidden_suite_sha256": hashes}


class Remote:
    def __init__(self, config, socket_dir):
        self.root = config["remote_root"].rstrip("/")
        self.python = config["remote_python"]
        self.bwrap = config.get("sandbox_bwrap")
        self.ssh = ["ssh", "-T", "-p", str(config["ssh_port"]), "-i", config["ssh_identity"],
                    "-o", "BatchMode=yes", "-o", "IdentitiesOnly=yes", "-o", "StrictHostKeyChecking=yes",
                    "-o", "ConnectTimeout=15", "-o", "ServerAliveInterval=30", "-o", "ServerAliveCountMax=3",
                    "-o", "ControlMaster=auto", "-o", "ControlPersist=60", "-o",
                    "ControlPath=" + str(Path(socket_dir) / ("ssh-" + hashlib.sha256(config["ssh_host"].encode()).hexdigest()[:12])), config["ssh_host"]]

    def run(self, command, data=None, check=True):
        result = subprocess.run(self.ssh + [command], input=data, capture_output=True)
        if check and result.returncode:
            raise RuntimeError(f"SSH exit {result.returncode}: " + result.stderr.decode(errors="replace")[-2000:])
        return result

    def put(self, local, relative):
        target = self.root + "/" + relative
        self.run("mkdir -p " + shlex.quote(str(Path(target).parent)) + " && cat > " +
                 shlex.quote(target), local.read_bytes())

    def json(self, relative):
        return json.loads(self.run("cat " + shlex.quote(self.root + "/" + relative)).stdout)

    def evaluate(self, candidate, suite, out, device, timeout, seed):
        cmd = [self.python, "-m", "kernel_bench", "run", "--candidate", candidate,
               "--suite", suite, "--out", out, "--device", str(device),
               "--timeout", str(timeout), "--rounds", "9", "--repeats", "64"]
        if seed is not None:
            cmd += ["--seed", str(seed)]
        if self.bwrap:
            cmd += ["--bwrap", self.bwrap]
        command = "cd " + shlex.quote(self.root) + " && " + shlex.join(cmd)
        started = time.monotonic()
        process = self.run(command, check=False)
        return process, time.monotonic() - started


class Campaign:
    def __init__(self, config, out, remote):
        self.config, self.out, self.remote = config, out, remote
        self.relative = out.relative_to(ROOT).as_posix()
        self.lock = threading.Lock()
        self.active = 0
        self.peak_active = 0
        self.key = os.environ.get(config["api_key_env"])

    def publish(self, path):
        self.remote.put(path, path.relative_to(ROOT).as_posix())

    def record(self, path, value):
        save(path, value)
        self.publish(path)

    def event(self, task, event, **fields):
        record = {"time": utc(), "task": task, "event": event, **fields}
        with self.lock:
            with (self.out / "events.jsonl").open("a") as f:
                f.write(json.dumps(record) + "\n")
            print(json.dumps(record), flush=True)

    def redact(self, message):
        return message.replace(self.key, "[REDACTED]") if self.key else message

    def call_model(self, payload, directory, timeout):
        self.record(directory / "request.json", payload)
        api = self.config.get("api", "chat_completions")
        endpoint = "/responses" if api == "responses" else "/chat/completions"
        headers = {"Content-Type": "application/json"}
        if self.key:
            headers["Authorization"] = "Bearer " + self.key
        request = urllib.request.Request(self.config["base_url"].rstrip("/") + endpoint,
                                         data=json.dumps(payload).encode(), headers=headers)
        started = time.monotonic()
        with self.lock:
            self.active += 1
            self.peak_active = max(self.peak_active, self.active)
        try:
            with urllib.request.urlopen(request, timeout=timeout) as response:
                raw = json.load(response)
            self.record(directory / "response.json", raw)
            normalized = normalize_response(raw, api)
            if api == "responses":
                self.record(directory / "normalized-response.json", normalized)
            return normalized, time.monotonic() - started
        finally:
            with self.lock:
                self.active -= 1

    def confirm_budget_timeout(self, task, suite, attempt, device, timeout, invalid):
        if (task not in kernel_v07.SPECS or self.config.get("turns") is not None
                or timeout >= self.config["case_timeout"] or not invalid):
            return False
        pattern = rf"RuntimeError: Baseline failed [a-z_]+ control failed: worker exceeded {timeout}s"
        if not all(re.fullmatch(pattern, item["error"]) for item in invalid):
            return False
        control = f"kernel_bench/candidates/{task}/control.py"
        output = (attempt/"budget-control").relative_to(ROOT).as_posix()
        process, seconds = self.remote.evaluate(control, suite, output, device, self.config["case_timeout"], None)
        check = self.remote.json(output + "/results.json")
        cases = check["cases"]
        expected = json.loads((ROOT/suite).read_text())["cases"]
        passed = process.returncode == 0 and [r["id"] for r in cases] == [r["id"] for r in expected] and all(
            r["status"] == "passed" for r in cases)
        self.record(attempt/"budget-control.json", {"passed": passed, "short_timeout": timeout,
                    "full_timeout": self.config["case_timeout"], "seconds": seconds})
        return passed

    def trial(self, task, device):
        directory = self.out / task
        directory.mkdir()
        started = time.monotonic()
        config = self.config
        pack = ROOT / "kernel_bench/taskpacks" / config.get("taskpack_version", "v0.3") / task
        metadata = json.loads((pack / "task.json").read_text())
        if metadata.get("validation_status") == "quarantined":
            state = {"task": task, "status": "invalid_baseline", "attempts": [],
                     "baseline_errors": [{"id": task, "error": metadata["quarantine_reason"]}],
                     "finished_at": utc(), "scaffold": SCAFFOLD}
            self.record(directory / "trial.json", state)
            self.event(task, "quarantined_before_model_call")
            return state
        prompt, case_count = public_prompt(pack, config)
        messages = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": prompt}]
        (directory / "prompt.md").write_text(SYSTEM + "\n\n" + prompt)
        self.publish(directory / "prompt.md")
        state = {"task": task, "status": "running", "started_at": utc(), "device": device,
                 "scaffold": SCAFFOLD, "model": config["model"], "seed": config["seed"],
                 "prompt_sha256": digest(directory / "prompt.md"), "attempts": []}
        self.record(directory / "trial.json", state)
        self.event(task, "started", gpu=device)
        evaluation_seconds = 0
        limit = config.get("turns")
        for turn in count(1) if limit is None else range(1, limit + 1):
            if (self.out / "STOP").exists():
                state["stopped_by_controller"] = True
                break
            remaining = config["wall_seconds"] - (time.monotonic() - started)
            public_limit = config.get("public_evaluation_seconds")
            gpu_remaining = math.inf if public_limit is None else public_limit - evaluation_seconds
            if remaining < 60 or gpu_remaining < 40:
                state["budget_exhausted"] = True
                state["stop_reason"] = "development_time" if remaining < 60 else "public_evaluation_time"
                break
            attempt = directory / f"attempt-{turn}"
            attempt.mkdir()
            entry = {"turn": turn, "status": "started"}
            state["attempts"].append(entry)
            payload = model_payload(config, messages)
            try:
                raw, elapsed = self.call_model(payload, attempt, min(config["model_timeout"], remaining - 30))
                entry.update(model_seconds=elapsed, usage=raw.get("usage"), response_model=raw.get("model"),
                             response_id=raw.get("id"),
                             system_fingerprint=raw.get("system_fingerprint"),
                             finish_reason=raw["choices"][0].get("finish_reason"))
                msg = raw["choices"][0]["message"]
                content = msg.get("content") or ""
                finalized = content.lstrip().startswith("FINAL\n")
                if finalized:
                    state["stop_reason"] = "model_finalized"
                if (self.out / "STOP").exists():
                    entry["status"] = "stopped_after_model_response"
                    self.record(directory / "trial.json", state)
                    break
                # Preserve provider reasoning in the trajectory, but feed back only its submitted answer.
                messages.extend(raw.get("assistant_history") or
                                [{"role": "assistant", "content": msg.get("content") or ""}])
                source = attempt / "submission.py"
                try:
                    code = extract_code(msg.get("content"), task)
                except (ValueError, SyntaxError) as exc:
                    entry.update(status="invalid_submission", error=str(exc))
                    limit_note = " The response reached its output-token limit." if entry["finish_reason"] == "length" else ""
                    messages.append({"role": "user", "content":
                                     f"Submission rejected: {exc}.{limit_note} Return a complete corrected file."})
                else:
                    source.write_text(code)
                    self.publish(source)
                    entry["submission_sha256"] = digest(source)
                    if finalized:
                        entry["status"] = "submitted_final"
                        break
                    left = config["wall_seconds"] - (time.monotonic() - started)
                    # Correctness/timing plus two fresh-process memory profiles per case.
                    timeout = int(min(config["case_timeout"], (min(left, gpu_remaining) - 20) / (3 * case_count)))
                    if timeout < 5:
                        entry["status"] = "budget_exhausted_before_evaluation"
                        state["budget_exhausted"] = True
                        state["stop_reason"] = "development_time" if left < gpu_remaining else "public_evaluation_time"
                        break
                    rel = attempt.relative_to(ROOT).as_posix()
                    self.event(task, "public_evaluation", turn=turn, gpu=device)
                    suite = f"kernel_bench/taskpacks/{config.get('taskpack_version', 'v0.3')}/{task}/public_cases.json"
                    process, seconds = self.remote.evaluate(rel + "/submission.py",
                        suite, rel + "/public", device,
                        timeout, None if task in kernel_v07.SPECS else config["seed"])
                    evaluation_seconds += seconds
                    (attempt / "grader.log").write_bytes(process.stdout + process.stderr)
                    self.publish(attempt / "grader.log")
                    result = self.remote.json(rel + "/public/results.json")
                    save(attempt / "public-results.json", result)
                    self.publish(attempt / "public-results.json")
                    entry.update(status="evaluated", evaluation_seconds=seconds, exit_code=process.returncode,
                                 rank=list(rank(result)), grader_results_sha256=digest(attempt / "public-results.json"))
                    invalid = baseline_errors(result)
                    if invalid and self.confirm_budget_timeout(task, suite, attempt, device, timeout, invalid):
                        entry.update(status="budget_exhausted_during_evaluation", incomplete_rank=entry.pop("rank"))
                        state.update(budget_exhausted=True,
                                     stop_reason="development_time" if left < gpu_remaining else "public_evaluation_time")
                        break
                    if invalid:
                        entry["status"] = "baseline_error"
                        state.update(status="invalid_baseline", baseline_errors=invalid, finished_at=utc(),
                                     public_evaluation_seconds=evaluation_seconds,
                                     development_seconds=time.monotonic()-started)
                        self.record(directory / "trial.json", state)
                        self.event(task, "invalid_baseline", cases=len(invalid))
                        return state
                    public_feedback = feedback(result)
                    self.record(attempt / "feedback.json", public_feedback)
                    label = str(turn) if limit is None else f"{turn}/{limit}"
                    messages.append({"role": "user", "content":
                        f"Public GPU feedback for submission {label}:\n" +
                        json.dumps(public_feedback) + "\nRevise to fix errors and improve latency. Return a complete file."})
                    self.event(task, "public_complete", turn=turn, rank=entry["rank"])
                if finalized:
                    break
            except Exception as exc:
                # A transport failure consumes this model-call slot; there are no invisible retries.
                error = self.redact(f"{type(exc).__name__}: {exc}")
                entry.update(status="infrastructure_error", error=error[:2000])
                state["stop_reason"] = "infrastructure_error"
                self.event(task, "attempt_error", turn=turn, error=entry["error"])
                break
            self.record(directory / "trial.json", state)
        else:
            state["stop_reason"] = "submission_limit"
        state.update(public_evaluation_seconds=evaluation_seconds,
                     development_seconds=time.monotonic() - started, frozen_at=utc())
        if (self.out / "STOP").exists():
            state.update(status="stopped", stop_reason="controller_stop")
            self.record(directory / "trial.json", state)
            return state
        return self.grade_final(task, device, state)

    def grade_final(self, task, device, state):
        directory = self.out / task
        config = self.config
        state["selection_policy"] = "last_response"
        attempts = state["attempts"]
        entry = attempts[-1] if attempts else {}
        if entry.get("status") == "infrastructure_error":
            state["status"] = "infrastructure_error"
        elif not entry.get("submission_sha256"):
            state["status"] = "no_evaluated_submission"
            state["final_turn"] = entry.get("turn")
        else:
            turn = entry["turn"]
            attempt = directory / f"attempt-{turn}"
            source = attempt / "submission.py"
            if digest(source) != entry["submission_sha256"]:
                raise ValueError("Final submission hash mismatch")
            frozen = directory / "submission.py"
            shutil.copyfile(source, frozen)
            self.publish(frozen)
            state.update(status="frozen", selected_turn=turn, final_turn=turn,
                         submission_sha256=digest(frozen), frozen_at=utc())
            self.record(directory / "trial.json", state)
            if entry["status"] == "evaluated":
                report = attempt/"public-results.json"
                if digest(report) != entry["grader_results_sha256"]:
                    raise ValueError("Final public results hash mismatch")
                result = json.loads(report.read_text())
            else:
                # Final acceptance has the full per-case timeout, including when
                # the development budget expired during the last public attempt.
                rel = directory.relative_to(ROOT).as_posix()
                version = config.get("taskpack_version", "v0.3")
                self.event(task, "final_public_evaluation", turn=turn)
                proc, elapsed = self.remote.evaluate(rel+"/submission.py",
                    f"kernel_bench/taskpacks/{version}/{task}/public_cases.json",
                    rel+"/final-public", device, config["case_timeout"],
                    None if task in kernel_v07.SPECS else config["seed"])
                result = self.remote.json(rel+"/final-public/results.json")
                state.update(final_public_seconds=elapsed, final_public_exit_code=proc.returncode)
                invalid = baseline_errors(result)
                if invalid:
                    state.update(status="invalid_baseline", baseline_errors=invalid, finished_at=utc())
                    self.record(directory/"trial.json", state)
                    return state
            state.update(public_summary=result["summary"], public_rank=list(rank(result)))
            # This path and all private case rows stay on the NAS; only aggregates leave the grader.
            private = f"kernel_bench/private/{config.get('taskpack_version', 'v0.3')}/{self.out.name}/{task}"
            self.event(task, "hidden_evaluation", gpu=device)
            process, seconds = self.remote.evaluate(frozen.relative_to(ROOT).as_posix(),
                private + "/suite.json", private + "/graded", device,
                config["case_timeout"], None if config.get("taskpack_version") in ("v0.5-h100-kernels", main_h100.PACK, kernel_v07.PACK, kernel_v08.PACK, kernel_v08.DIAGNOSTIC_PACK, kernel_v081.PACK) else config["seed"] + 900000)
            script = ("import json,pathlib,hashlib,collections; p=pathlib.Path(" +
                      repr(self.remote.root + "/" + private + "/graded/results.json") + "); "
                      "from kernel_bench.agent_trial import baseline_errors; "
                      "r=json.loads(p.read_text()); print(json.dumps({'summary':r['summary'],"
                      "'baseline_errors':baseline_errors(r, private=True),"
                      "'status_counts':dict(collections.Counter(c['status'] for c in r['cases'])),"
                      "'results_sha256':hashlib.sha256(p.read_bytes()).hexdigest(),"
                      "'suite_sha256':hashlib.sha256(p.parent.parent.joinpath('suite.json').read_bytes()).hexdigest()}))")
            aggregate = json.loads(self.remote.run(shlex.join([self.remote.python, "-c", script])).stdout)
            self.record(directory / "hidden-summary.json", aggregate)
            state.update(status="completed", hidden_summary=aggregate, hidden_evaluation_seconds=seconds,
                         hidden_exit_code=process.returncode, finished_at=utc())
            if aggregate.get("baseline_errors"):
                state.update(status="invalid_baseline", baseline_errors=aggregate["baseline_errors"])
            self.event(task, "completed", public_correct=state["public_rank"][0],
                       hidden_correct=aggregate["status_counts"].get("passed", 0))
        self.record(directory / "trial.json", state)
        if state.get("status") in ("completed", "no_evaluated_submission"):
            from .artifact_store import compact_task
            try:
                compact_task(directory)
            except (OSError, ValueError, RuntimeError, zipfile.BadZipFile) as exc:
                print("Artifact compaction deferred: " + str(exc), file=sys.stderr, flush=True)
        return state


def validate_config(config):
    if config.get("api", "chat_completions") not in ("chat_completions", "responses"):
        raise ValueError("Unsupported model API")
    if not 1 <= config["concurrency"] <= 4:
        raise ValueError("Concurrency must be between 1 and 4")
    if len(set(config["devices"][:config["concurrency"]])) < config["concurrency"]:
        raise ValueError("Each concurrent worker requires a different GPU")
    limit = config.get("turns")
    if limit is not None and (type(limit) is not int or limit < 1):
        raise ValueError("turns must be a positive integer or null for time-budgeted submissions")
    public_limit = config.get("public_evaluation_seconds")
    if public_limit is not None and (type(public_limit) is not int or public_limit <= 0):
        raise ValueError("public_evaluation_seconds must be a positive integer or null")
    for key in ("max_output_tokens", "model_timeout", "wall_seconds", "case_timeout"):
        if config[key] <= 0:
            raise ValueError(key + " must be positive")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--config", type=Path, required=True)
    parser.add_argument("--out", type=Path, required=True)
    args = parser.parse_args()
    config = json.loads(args.config.read_text())
    config.setdefault("turns", None)
    default_packs = {LEGACY_PROTOCOL: "v0.3", main_h100.VERSION: main_h100.PACK,
                     kernel_v07.VERSION: kernel_v07.PACK, kernel_v08.VERSION: kernel_v08.PACK, kernel_v081.VERSION: kernel_v081.PACK}
    config.setdefault("taskpack_version", default_packs.get(config.get("protocol_version"), kernel_v081.PACK))
    protocols = {"v0.3": LEGACY_PROTOCOL, "v0.4-sparse": LEGACY_PROTOCOL, "v0.5-h100-kernels": LEGACY_PROTOCOL,
                 main_h100.PACK: main_h100.VERSION, kernel_v07.PACK: kernel_v07.VERSION,
                 kernel_v08.PACK: kernel_v08.VERSION, kernel_v08.DIAGNOSTIC_PACK: kernel_v08.VERSION, kernel_v081.PACK: kernel_v081.VERSION}
    protocol = protocols.get(config["taskpack_version"])
    config.setdefault("protocol_version", protocol)
    if protocol is None or config["protocol_version"] != protocol:
        raise ValueError("Protocol and public packs must match this grader; replay older trials from their source snapshot")
    validate_config(config)
    out = args.out.resolve()
    if not out.is_relative_to(ROOT / "kernel_bench/results"):
        raise ValueError("Output must be a new directory under kernel_bench/results")
    out.mkdir(parents=True, exist_ok=False)
    catalog_name = {"v0.3": "task_catalog.json", "v0.4-sparse": "sparse_catalog.json",
                    "v0.5-h100-kernels": "h100_kernel_catalog.json",
                    kernel_v081.PACK: "kernel_catalog_v081.json", kernel_v08.PACK: "kernel_catalog_v08.json", kernel_v08.DIAGNOSTIC_PACK: "kernel_catalog_v08_diagnostics.json",
                    kernel_v07.PACK: "kernel_catalog_v07.json", main_h100.PACK: "h100_main_catalog_v06.json"}[config["taskpack_version"]]
    available = {t["id"] for t in json.loads((ROOT / "kernel_bench" / catalog_name).read_text())["tasks"]}
    tasks = config.get("tasks") or sorted(available)
    if not set(tasks) <= available:
        raise ValueError("Tasks must belong to the selected version of public packs")
    if len(set(tasks)) != len(tasks):
        raise ValueError("Duplicate task IDs")
    with tempfile.TemporaryDirectory(prefix="kb-agent-") as sockets:
        remote = Remote(config, sockets)
        remote.run("true")
        campaign = Campaign(config, out, remote)
        config.update(scaffold=SCAFFOLD, started_at=utc(), tasks=tasks,
                      scaffold_sha256=digest(Path(__file__)))
        config["public_case_counts"] = {task: len(json.loads((ROOT / "kernel_bench/taskpacks" /
            config["taskpack_version"] / task / "public_cases.json").read_text())["cases"]) for task in tasks}
        campaign.record(out / "config.json", config)
        # Freeze grader and public-pack identity before any model call.
        manifest = {str(p.relative_to(ROOT)): digest(p) for p in sorted((ROOT/"kernel_bench").rglob("*"))
                    if p.is_file() and not set(p.relative_to(ROOT).parts) & {"results", "private", "artifacts", "__pycache__"}}
        campaign.record(out / "source-manifest.json", manifest)
        verification = """import json,hashlib,pathlib,sys
root=pathlib.Path(sys.argv[1]); manifest=json.load(sys.stdin)
bad=[name for name,h in manifest.items() if not (root/name).is_file() or hashlib.sha256((root/name).read_bytes()).hexdigest()!=h]
assert not bad, bad
print('Local/NAS source hashes match:',len(manifest))
"""
        remote.run(shlex.join([remote.python, "-c", verification, remote.root]), json.dumps(manifest).encode())
        private_setup = ("import json,sys; from kernel_bench.agent_trial import prepare_private; "
                         "print(json.dumps(prepare_private(sys.argv[1],sys.argv[2],json.loads(sys.argv[3]),sys.argv[4],json.loads(sys.argv[5]))))")
        prepared = remote.run(shlex.join([remote.python, "-c", private_setup, remote.root, out.name,
                                         json.dumps(tasks), config["taskpack_version"],
                                         json.dumps(config.get("private_reference"))]))
        config.update(json.loads(prepared.stdout))
        campaign.record(out / "config.json", config)
        states = []

        def worker(device, assigned, active_campaign=campaign):
            completed = []
            for task in assigned:
                if (out / "STOP").exists():
                    break
                try:
                    completed.append(active_campaign.trial(task, device))
                except Exception as exc:
                    path = out / task / "trial.json"
                    state = json.loads(path.read_text()) if path.exists() else {"task": task}
                    state.update(status="infrastructure_error", error=campaign.redact(str(exc))[:2000])
                    campaign.record(path, state)
                    campaign.event(task, "trial_error", error=state["error"])
                    completed.append(state)
            return completed

        single_gpu_tasks = [task for task in tasks if task != kernel_v07.MOE]
        if kernel_v07.MOE in tasks:
            # Both nodes use the same NAS directory for the immutable submission and private split.
            moe_config = dict(config, **config.get("moe_remote", {}))
            if moe_config["remote_root"] != config["remote_root"]:
                raise ValueError("The two nodes must share remote_root on NAS")
            moe_remote = Remote(moe_config, sockets)
            moe_devices = [str(d) for d in config.get("moe_devices", range(8))]
            command = ["nvidia-smi", "-i", ",".join(moe_devices), "--query-gpu=name", "--format=csv,noheader"]
            names = moe_remote.run(shlex.join(command), check=False)
            if len(set(moe_devices)) == 8 and names.returncode == 0 and len(names.stdout.splitlines()) == 8 and all(
                    b"B200" in name for name in names.stdout.splitlines()):
                moe_remote.run("test -r " + shlex.quote(moe_remote.root + "/kernel_bench/private/" +
                               config["taskpack_version"] + "/" + out.name + "/" + kernel_v07.MOE + "/suite.json"))
                moe_campaign = Campaign(config, out, moe_remote)
                states.extend(worker(",".join(moe_devices), [kernel_v07.MOE], moe_campaign))
                campaign.peak_active = max(campaign.peak_active, moe_campaign.peak_active)
            else:
                state = dict(task=kernel_v07.MOE, status="hardware_unavailable", attempts=[])
                campaign.record(out / kernel_v07.MOE / "trial.json", state)
                campaign.event(kernel_v07.MOE, "hardware_unavailable")
                states.append(state)
        with ThreadPoolExecutor(max_workers=config["concurrency"]) as pool:
            futures = [pool.submit(worker, config["devices"][i], single_gpu_tasks[i::config["concurrency"]])
                       for i in range(config["concurrency"])]
            for future in as_completed(futures):
                states.extend(future.result())
        campaign.record(out / "campaign.json", {"finished_at": utc(), "peak_model_concurrency": campaign.peak_active,
                                               "tasks": sorted(states, key=lambda x:x["task"])})
        campaign.publish(out / "events.jsonl")
        print("CAMPAIGN", out, flush=True)


if __name__ == "__main__":
    main()