File size: 27,938 Bytes
0f775e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a10d86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f775e2
 
 
 
9f1b277
 
 
 
 
 
0f775e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f1b277
 
 
0f775e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Generate a complete kernel-generation task directory from a TaskSpec.

    python _factory/build.py specs/kda_forward.py          # writes ../kda-forward/

Everything the four hand-built tasks converged on is baked in here, so it cannot drift between tasks:

  * reward = achieved metric (uncapped leaderboard), 0 if incorrect — no gold solution, no oracle
  * correctness gated against an EMBEDDED private copy of the reference (editing /app cannot affect grading)
  * timing on FRESH inputs every rep + the timed call's own output validated  (defeats memoize-and-replay)
  * min-over-reps timing (reproducible on a shared GPU)
  * bf16/fp8 precision policy + an explicit "what the tolerance does NOT permit" faithfulness clause
  * a grading-transparency section so the contract has no surprises
"""
import pathlib
import shutil
import sys

HERE = pathlib.Path(__file__).resolve().parent
LANE = HERE.parent
SHARED = ("CLAUDE.md", "PROCESS_MANAGEMENT.md", "restrict-network.sh", "docker-compose.yaml")
# sourced from _factory/shared/ so regenerating any task never self-copies

# --------------------------------------------------------------------------------------------------
# comparison helpers, injected into both the grader and measure.py
# --------------------------------------------------------------------------------------------------
CHECK_TENSOR = '''
def _is_exact(t):
    """Integer/bool tensors are compared EXACTLY: .float() is lossy above 2**24, so two distinct large
    ids (page ids, token ids, indices) can compare equal and let a wrong kernel pass."""
    return t.dtype in (torch.int8, torch.int16, torch.int32, torch.int64, torch.uint8, torch.bool)


def _check(out, ref):
    """-> (ok, value, msg). Exact for integer/bool; relative Frobenius error otherwise."""
    if out is None or tuple(out.shape) != tuple(ref.shape):
        return False, 1.0, "bad/None shape"
    if _is_exact(ref):
        bad = int((out != ref).sum())
        return bad == 0, float(bad), ("exact match" if bad == 0 else f"{bad} elements differ")
    e = float((out.float() - ref.float()).norm() / (ref.float().norm() + 1e-12))
    return e <= TOL, e, f"relerr {e:.2e}"
'''

CHECK_TUPLE = '''
def _check(out, ref):
    """-> (ok, value, msg). value = MAX relative error across the returned tuple."""
    if out is None or len(out) != len(NAMES):
        return False, 1.0, f"expected a {len(NAMES)}-tuple {NAMES}"
    per = []
    for n, a, b in zip(NAMES, out, ref):
        if a is None or tuple(a.shape) != tuple(b.shape):
            return False, 1.0, f"{n} bad shape"
        if b.dtype in (torch.int8, torch.int16, torch.int32, torch.int64, torch.uint8, torch.bool):
            # exact: .float() is lossy above 2**24 and would let distinct large ids compare equal
            bad = int((a != b).sum())
            if bad:
                return False, 1.0, f"{n}: {bad} elements differ"
            continue
        per.append((n, float((a.float() - b.float()).norm() / (b.float().norm() + 1e-12))))
    if not per:
        return True, 0.0, "all integer outputs exact"
    wn, wv = max(per, key=lambda x: x[1])
    return wv <= TOL, wv, f"worst {wn} {wv:.2e}"
'''

CHECK_ROWWISE = '''
def _check(out, ref):
    """-> (ok, value, msg). value = FRACTION of trailing-dim rows within TOL."""
    if out is None or tuple(out.shape) != tuple(ref.shape):
        return False, 0.0, "bad/None shape"
    num = (out.float() - ref.float()).norm(dim=-1)
    den = ref.float().norm(dim=-1) + 1e-6
    frac = float((num / den <= TOL).float().mean())
    return frac >= ROW_PASS, frac, f"{frac*100:.2f}% rows pass"
'''

CHECKS = {"tensor": CHECK_TENSOR, "tuple": CHECK_TUPLE, "rowwise": CHECK_ROWWISE}

# --------------------------------------------------------------------------------------------------
VERIFY = '''"""{name} verifier — correctness gate + achieved-{metric} SPEED LEADERBOARD (uncapped).

    reward = 0                                     if the submission is incorrect
    reward = geomean over graded shapes of {metric} otherwise

GENERATED by _factory/build.py — do not edit here; edit the spec and regenerate.

There is no gold solution and no oracle: the score is an absolute hardware metric, so it is hardware-portable
by construction and nothing has to be vendored, sealed, or re-benchmarked.

CORRECTNESS is a hard gate, checked against an INDEPENDENT (embedded) copy of the reference at every graded
shape including the timed ones, so editing /app/reference.py cannot affect grading and a fast wrong kernel
scores 0.

ANTI-CHEAT on the timing path: every timed rep runs on FRESHLY generated inputs, and the output of the last
timed rep is itself validated against the reference for those exact inputs. A submission that memoizes a
result and replays it fails the gate instead of posting an inflated number. Warm-up runs on a separate
throwaway input set, so ordinary shape-keyed JIT/autotune caching is not penalised.

WORK is attributed by a CANONICAL formula that depends only on the shape, never on the implementation, so all
submissions are credited identically and the ranking is a pure speed ranking.
"""
import importlib.util
import json
import math
import os
import sys
import traceback

{imports}

REWARD_DIR = "/logs/verifier"
MODULE_PATH = "/app/{module}"
TOL = {tol!r}
{extra_consts}
GRADER_SHAPES = {grader_shapes!r}
CORRECT_SHAPES = {correct_shapes!r}

sys.path.insert(0, "/app")

{flops_src}

{reference_src}

{make_inputs_src}

{check_src}

def _bench_fresh(fn, mkargs, reps=5, warm=3):
    """Time `fn` on FRESH inputs every rep -> (min_seconds, timed_ok). See the module docstring."""
    wargs = mkargs(0)
    for _ in range(warm):
        fn(*wargs)
    torch.cuda.synchronize()
    del wargs
    torch.cuda.empty_cache()

    best, timed_ok = float("inf"), True
    for i in range(reps):
        args = mkargs(10_000 + i)
        s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
        s.record()
        out = fn(*args)
        e.record()
        torch.cuda.synchronize()
        best = min(best, s.elapsed_time(e))
        if i == reps - 1:
            timed_ok = _check(out, {ref_func}(*args))[0]
        del args, out
        torch.cuda.empty_cache()
    return best / 1e3, timed_ok


def _geomean(xs):
    return math.exp(sum(math.log(max(v, 1e-9)) for v in xs) / len(xs)) if xs else 0.0


def main():
    details, correct_gate, geo = {{}}, False, 0.0
    try:
        spec = importlib.util.spec_from_file_location("submission", MODULE_PATH)
        m = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(m)
        fn = m.{func}

        corr_ok, msg = True, ""
        for i, shp in enumerate(CORRECT_SHAPES):
            args = _mk(*shp, seed=10 + i)
            ok, val, m_ = _check(fn(*args), {ref_func}(*args))
            if not ok:
                corr_ok, msg = False, f"cfg{{i}} {{shp}} {{m_}}"
                break
            del args
            torch.cuda.empty_cache()
        details["correct_msg"] = msg or "all correctness shapes pass"

        vals, per_shape, perf_ok = [], [], corr_ok
        for i, shp in enumerate(GRADER_SHAPES):
            args = _mk(*shp, seed=100 + i)
            ok, val, m_ = _check(fn(*args), {ref_func}(*args))
            if not ok:
                perf_ok = False
            del args
            torch.cuda.empty_cache()
            t, timed_ok = _bench_fresh(fn, lambda s, _p=shp: _mk(*_p, seed=s))
            if not timed_ok:
                perf_ok = False
            v = canonical_work(*shp) / t / {scale} if t > 0 else 0.0
            vals.append(v)
            per_shape.append({{"shape": list(shp), "{mkey}": round(v, 3), "ms": round(t * 1e3, 3),
                              "check": m_, "timed_ok": timed_ok}})
        geo = _geomean(vals)
        details.update(per_shape=per_shape, geomean=round(geo, 4), perf_size_ok=perf_ok)
        correct_gate = corr_ok and perf_ok
    except Exception as e:
        details["error"] = f"{{e.__class__.__name__}}: {{e}}"[:220]
        details["trace"] = traceback.format_exc()[-800:]

    reward = round(geo, 4) if correct_gate else 0.0
    os.makedirs(REWARD_DIR, exist_ok=True)
    json.dump({{"reward": reward, "correct": 1.0 if correct_gate else 0.0,
               "geomean": round(geo, 4), "metric": "{metric} (geomean over graded shapes)"}},
              open(f"{{REWARD_DIR}}/reward.json", "w"), indent=2)
    open(f"{{REWARD_DIR}}/reward.txt", "w").write(str(reward))
    json.dump(details, open(f"{{REWARD_DIR}}/details.json", "w"), indent=2, default=str)
    print("reward:", reward, "{metric} | correct:", 1.0 if correct_gate else 0.0)


main()
'''

# --------------------------------------------------------------------------------------------------
MEASURE = '''"""Self-assessment tool — your correctness + achieved {metric} across a RANGE of shapes.

    python /app/measure.py            # the graded regime
    python /app/measure.py --quick    # smaller sizes for fast iteration

You are scored on the **geomean achieved {metric}** — NOT one fixed size, and the leaderboard is UNCAPPED
(higher is always better). The shapes below are a DIFFERENT sample from the same regime the grader uses, so
optimize for GENERALITY. Work is counted with the same shape-only formula the grader uses, so the number
printed here is computed exactly as your score is.

GENERATED by _factory/build.py.
"""
import argparse
import math
import sys

{imports}

sys.path.insert(0, "/app")
from reference import {func} as _ref
from {mod_stem} import {func} as _agent

TOL = {tol!r}
{extra_consts}
FULL = {measure_shapes!r}
QUICK = {measure_quick_shapes!r}

{flops_src}

{make_inputs_src}

{check_src}

def _bench(fn, reps=8, warm=3):
    for _ in range(warm):
        fn()
    torch.cuda.synchronize()
    best = float("inf")
    for _ in range(reps):
        s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
        s.record()
        fn()
        e.record()
        torch.cuda.synchronize()
        best = min(best, s.elapsed_time(e))
    return best / 1e3


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--quick", action="store_true")
    a = ap.parse_args()
    shapes = QUICK if a.quick else FULL
    print(f"geomean over {{len(shapes)}} shapes ({{'quick' if a.quick else 'full'}}); the grader uses "
          f"DIFFERENT sizes in the same regime — optimize for generality\\n")
    vals, allok = [], True
    for shp in shapes:
        args = _mk(*shp, seed=sum(int(x) for x in shp) % 9973)
        ref = _ref(*args)
        try:
            out = _agent(*args)
        except Exception as ex:
            print(f"  {{shp}}: RAISED {{type(ex).__name__}}: {{str(ex)[:70]}}")
            allok = False
            continue
        ok, val, msg = _check(out, ref)
        allok = allok and ok
        t = _bench(lambda: _agent(*args))
        v = canonical_work(*shp) / t / {scale} if t > 0 else 0.0
        vals.append(v)
        print(f"  {{str(shp):28s}} {{t*1e3:9.2f}} ms | {{v:9.2f}} {metric} | {{msg}} {{'ok' if ok else 'FAIL'}}")
        del args, ref, out
        torch.cuda.empty_cache()
    geo = math.exp(sum(math.log(max(v, 1e-9)) for v in vals) / len(vals)) if vals else 0.0
    print(f"\\n  => GEOMEAN {{geo:.2f}} {metric}   "
          f"({{'all correct' if allok else 'SOME WRONG — a wrong kernel scores 0, fix correctness first'}})")
    print("     This IS your score, and it is uncapped — higher is always better. Keep pushing.")


if __name__ == "__main__":
    main()
'''

# --------------------------------------------------------------------------------------------------
STUB = '''"""Your implementation goes here.

Replace the body of `{func}` with a FAST implementation that reproduces the output of /app/reference.py
(same signature, same numerics within tolerance) but is much faster — see /app/instruction.md.
Run `python /app/measure.py` to check your correctness and achieved {metric}.

You may add helper modules, Triton kernels, CUDA extensions, caches, etc. — only this function's name,
signature and returned value are fixed by the contract.
"""


def {signature}:
{returns_doc_indented}
    raise NotImplementedError("Implement a fast {func} in /app/{module}")
'''

DOCKERFILE = '''# Kernel-generation task: {title}
#
# {blurb_wrapped}
#
# SCORING: correctness is a hard gate; the score is achieved {metric} (uncapped leaderboard, 0 if wrong).
# There is no gold solution and no oracle, so nothing has to be vendored or sealed.
#
# TOOLCHAIN POLICY: the agent writes the kernel with Triton (+Gluon), CUDA C++ via nvcc, CUTLASS headers, or
# the CuTe DSL. Enforcement is by ABSENCE, not by scanning: only the permitted toolchain is installed and
# there is no internet, so nothing else can be obtained.
#
# GENERATED by _factory/build.py.
FROM {base_image}

# NOTE: every heavy layer comes FIRST and depends only on {{base_image, pip_extra}}, so all tasks in this
# lane share the same cached layers. The task-specific COPYs are LAST. Do not reorder.
RUN pip install --break-system-packages --no-cache-dir {pip_extra} && \\
    apt-get update && apt-get install -y --no-install-recommends iptables iproute2 curl ca-certificates build-essential git && \\
    curl -LsSf https://astral.sh/uv/install.sh | sh && \\
    /root/.local/bin/uv tool install mini-swe-agent
# header-only CUTLASS for the agent's CUDA/CuTe route
RUN git clone --depth 1 https://github.com/NVIDIA/cutlass /opt/cutlass && rm -rf /opt/cutlass/.git
# pre-bake Claude Code; harbor's claude_code.install() skips when present
RUN curl -fsSL https://deb.nodesource.com/setup_22.x | bash - && \\
    apt-get install -y nodejs procps && \\
    npm install -g @anthropic-ai/claude-code && claude --version
ENV PATH=/root/.local/bin:$PATH
ENV DISABLE_TELEMETRY=1 DISABLE_AUTOUPDATER=1 DISABLE_ERROR_REPORTING=1 CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1

COPY restrict-network.sh /app/restrict-network.sh
RUN chmod +x /app/restrict-network.sh
# strip apt sources LAST so harbor's post-firewall apt step is a no-op that succeeds
RUN rm -rf /var/lib/apt/lists/* /etc/apt/sources.list /etc/apt/sources.list.d

WORKDIR /app
COPY CLAUDE.md PROCESS_MANAGEMENT.md /app/

# task-specific files LAST so the layers above stay shared across every task
COPY reference.py /app/reference.py
COPY measure.py /app/measure.py
COPY {module} /app/{module}
'''

FAITHFULNESS = '''
### What the tolerance does NOT permit

The tolerance exists **only** to absorb low-precision arithmetic noise. You are responsible for a **faithful
implementation of the specified computation**. It is not a budget to spend on approximation. The following
are wrong answers even if they happen to land inside the tolerance at some shape:

- changing the algorithm to something that merely *approximates* the spec (dropping terms, truncating a
  series, low-rank or sketched substitutes, skipping a correction term);
- shortening the computation (fewer iterations/steps than specified, early exit on a heuristic, subsampling
  or striding over the sequence, ignoring positions whose contribution "looks small");
- computing at a coarser granularity than the spec (sharing a decay, scale, or normaliser across positions
  that the spec gives their own);
- anything whose error **grows** with sequence length, batch, or head count.

A faithful bf16/fp8 kernel's error is *noise*: it stays flat as the problem grows and sits an order of
magnitude below the gate. An approximation's error is *bias*: it scales with the problem. The graded shapes
are deliberately large, so the difference shows up.
'''

INSTRUCTION = '''# {title}

You are given a **correct but slow** reference at **`/app/reference.py`** — `{signature}`. **Read it, run it, profile it.**

Write **`/app/{module}`** with the **same signature** and the **same numerical output**, but **as fast as you can make it**.

```python
def {signature}:
    ...
```

## The computation (this is the exact spec)

{spec_md}

## The contract (fixed — do not change these)

{contract_md}

{regime_md}

## How success is decided (runs on GPU)

**1. Correctness — a required gate.** {correctness_md} A wrong kernel scores **0**, no matter how fast.

**2. Performance — this is your score, and it is an UNCAPPED leaderboard.**

```
reward = geomean over graded shapes of ( canonical_work(shape) / your_runtime )   [{metric}]
reward = 0   if the submission is wrong at any graded shape
```

`canonical_work` depends **only on the shape**, never on how you implemented it, so every submission is
credited the same work and this is a pure speed ranking in useful units:

```
{flops_formula}
```

**There is no cap and no target.** Higher {metric} is always a strictly better score, so **push the
performance as hard as you can**. Getting a correct implementation is the *start* of the task, not the end of
it. Once correct, spend the entire remainder of your budget profiling and optimising, re-checking correctness
after every change. **Use your full time budget.**

Run **`python /app/measure.py`** at any point to see your per-shape and geomean {metric} plus correctness.

## Where the performance comes from

{perf_md}

## Precision and faithfulness (read this)

{precision_md}
{faithfulness}
## What's available

- **Triton 3.6** (with Gluon), **CUDA C++ via `nvcc`** (`torch.utils.cpp_extension.load` for an inline
  extension), header-only **CUTLASS** at `/opt/cutlass/include`, and the **CuTe DSL**
  (`nvidia-cutlass-dsl`). C++ / CuTe DSL is the encouraged route; Triton is fully supported.
- `torch` 2.11 (CUDA 12.8) and `einops` for bookkeeping.
- A GPU with compute capability **sm≥90**, so fp8, TMA and wgmma/tcgen05-class instructions exist.
  The exact part is deliberately **not** stated: query it and tune to what you actually find.

```python
p = torch.cuda.get_device_properties(0)
p.name, p.major, p.minor          # part and compute capability
p.multi_processor_count           # SM count -- size your persistent grid from this, never a constant
p.total_memory, p.regs_per_multiprocessor, p.max_threads_per_multi_processor
p.shared_memory_per_block_optin   # opt-in dynamic smem, the number that matters for big tiles
```

  `nvidia-smi --query-gpu=name,memory.total,clocks.max.sm --format=csv` and `nvidia-smi -q -d CLOCK`
  give clocks; measure achieved HBM bandwidth with a large stream-copy rather than trusting a
  datasheet figure. **Do not hardcode an SM count, a tile size derived from one, or a peak
  FLOP/bandwidth constant** — the same submission is graded on whatever device it lands on, and the
  score is an absolute metric, so a kernel tuned to a machine it never sees is just slower.
- **No internet access.** `pip install` and cloning repos are blocked. Everything you are permitted to use is
  already installed, and no library implementation of this kernel exists on the machine.
- Manage any long-running background job (a build, an `ncu`/`nsys` profile) by its **recorded PID** — see
  `/app/CLAUDE.md` and `/app/PROCESS_MANAGEMENT.md`.
- **Profilers.** `nsys` works here and answers the first question — is the time actually inside your
  kernel, or in launch gaps and dispatch? `ncu` reads GPU performance counters, which the container may
  not be permitted to access: if it prints `ERR_NVGPUCTRPERM`, counters are unavailable on this run.
  That is an environment permission, not something you can fix from inside — fall back to `nsys` plus
  A/B ablation (change one thing, re-time it) instead of spending your budget fighting it. Note that
  `ncu --version` succeeds either way; it never touches a counter.

## How the grading actually runs (so there are no surprises)

- **`/app/{module}` is the only file that is graded.** The grader imports `{func}` from it and reads nothing
  else from `/app`.
- **The grader is not on this machine while you work.** It is copied in only after your session ends and it
  carries its **own private copy of the reference** and its own input generator. Editing `/app/reference.py`
  or `/app/measure.py` is allowed — they are yours to experiment with — but it has **no effect whatsoever on
  your score**. Do not spend budget on them.
- **Every timed repetition uses freshly generated inputs**, and the output of a timed call is itself checked
  against the reference. Caching or memoizing a result and replaying it fails the correctness gate rather
  than producing a fast measurement. Ordinary shape-keyed JIT/autotune caching is fine and is not penalised.
- **The timed shapes are correctness-checked too.** Being correct only at the small shapes scores **0**.
- Inputs are random each grade and the graded shapes are not the ones in `measure.py`.
'''

TASK_TOML = '''schema_version = "1.1"

[task]
name = "mle-bench/{name}"
description = "{description}"
authors = []
keywords = [{keywords}]

[metadata]
suite = "mle-bench"
group = "kernel-generation"
level = "1.0"
difficulty = "hard"
category = "mle"
tags = [ "mle", "kernel-generation", "kernels", "gpu", "real-world",]

[verifier]
timeout_sec = {verifier_timeout_sec}

[agent]
timeout_sec = {agent_timeout_sec}

# GPU request: honored by Modal/GKE/Daytona. On the local docker backend set environment.override_gpus: 0
# in the job config and attach a GPU via configs/gpu_overlay_nvidia.yaml (see RUNNING.md §5).
# Profiling: `ncu` needs GPU performance counters — the runner must add the SYS_ADMIN capability
# (docker `--cap-add SYS_ADMIN`) or the host must set NVreg_RestrictProfilingToAdminUsers=0.
# Without it ncu exits with ERR_NVGPUCTRPERM. `nsys` works without any extra capability.
[environment]
build_timeout_sec = 3600.0
cpus = 8
memory_mb = {memory_mb}
storage_mb = 40960
gpus = {gpus}
network_mode = "public"
mcp_servers = []

[verifier.env]

[environment.env]

[solution.env]
'''

RUN_MD = '''# Running `{name}`

{blurb}

|  |  |
|---|---|
| **Task id** | `mle-bench/{name}` |
| **Group** | `kernel-generation` |
| **GPUs** | {gpus} |
| **Agent edits** | `/app/{module}` |
| **Score** | achieved **{metric}** (uncapped speed leaderboard), `0` if incorrect |
| **Grade output** | `tests/test.sh` -> `/logs/verifier/reward.json` |

## Run through harbor

```bash
harbor run --dataset-path kernel-generation/kernels/{name} --task-name {name} \\
  --agent claude-code --model anthropic/claude-opus-4-1 -e docker
```

## Run manually

```bash
cd kernel-generation/kernels/{name}
docker build -t {name} environment/
docker run -d --name v --gpus '"device=0"' --shm-size=8g --entrypoint sleep {name} infinity
docker cp tests v:/tests && docker exec v bash /tests/test.sh   # untouched start -> reward 0.0
docker rm -f v
```

Use an **idle** GPU: the score is a timing measurement.

## Design

Correctness is a hard gate; the score is an absolute hardware metric ({metric}), so the task is
hardware-portable and needs no gold solution, no oracle, and nothing vendored or sealed.

Anti-cheat is structural: the image holds only the permitted toolchain and has no internet; the grader is
copied in at grade time with its own private copy of the reference; and every timed rep runs on fresh inputs
with the timed output itself validated, so memoize-and-replay fails the gate.

Generated by `_factory/build.py` — edit the spec and regenerate rather than editing this task by hand.
'''


def _indent(text, n=4):
    pad = " " * n
    return "\n".join(pad + ln if ln.strip() else ln for ln in text.strip("\n").split("\n"))


def build(spec, out_root=LANE):
    spec.validate()
    d = pathlib.Path(out_root) / spec.name
    (d / "environment").mkdir(parents=True, exist_ok=True)
    (d / "tests").mkdir(parents=True, exist_ok=True)

    scale = {"TFLOP/s": "1e12", "GB/s": "2**30", "tokens/s": "1"}[spec.metric]
    mkey = {"TFLOP/s": "tflops", "GB/s": "gbps", "tokens/s": "toks"}[spec.metric]
    extra = ""
    if spec.compare == "tuple":
        extra = f"NAMES = {spec.tuple_names!r}\n"
    elif spec.compare == "rowwise":
        extra = f"ROW_PASS = {spec.row_pass!r}\n"
    imports = spec.reference_imports or "import torch"
    common = dict(name=spec.name, metric=spec.metric, module=spec.module, func=spec.func,
                  tol=spec.tol, extra_consts=extra, imports=imports, scale=scale, mkey=mkey,
                  flops_src=spec.flops_src.strip("\n"), make_inputs_src=spec.make_inputs_src.strip("\n"),
                  check_src=CHECKS[spec.compare], ref_func="_ref")

    # reference.py given to the agent (its public name), and the grader's embedded private copy (_ref)
    (d / "environment" / "reference.py").write_text(
        f'"""Reference implementation — the CORRECTNESS SPEC for `{spec.func}`.\n\n'
        f"This is correct but slow. It defines exactly what your kernel must reproduce; its speed has no\n"
        f"bearing on your score, which is an absolute {spec.metric} number. GENERATED by _factory/build.py.\n"
        f'"""\n{imports}\n\n\n{spec.reference_src.strip()}\n')
    (d / "tests" / "verify_env.py").write_text(VERIFY.format(
        grader_shapes=spec.grader_shapes, correct_shapes=spec.correct_shapes,
        reference_src=spec.reference_src.strip().replace(f"def {spec.func}(", "def _ref(", 1), **common))
    (d / "tests" / "test.sh").write_text(
        "#!/bin/bash\n# GENERATED by _factory/build.py. python3 (not python): some CUDA bases lack the symlink.\n"
        "set -u\nmkdir -p /logs/verifier\npython3 /tests/verify_env.py\n")
    (d / "tests" / "test.sh").chmod(0o755)
    (d / "environment" / "measure.py").write_text(MEASURE.format(
        mod_stem=spec.module[:-3], measure_shapes=spec.measure_shapes or spec.grader_shapes,
        measure_quick_shapes=spec.measure_quick_shapes or spec.correct_shapes, **common))
    (d / "environment" / spec.module).write_text(STUB.format(
        func=spec.func, module=spec.module, metric=spec.metric, signature=spec.signature,
        returns_doc_indented=_indent(f'"""{spec.returns_doc.strip()}\n"""')))
    (d / "environment" / "Dockerfile").write_text(DOCKERFILE.format(
        title=spec.title, blurb_wrapped=spec.blurb.replace("\n", "\n# "), metric=spec.metric,
        base_image=spec.base_image, module=spec.module, pip_extra=spec.pip_extra))
    (d / "instruction.md").write_text(INSTRUCTION.format(
        title=spec.title, signature=spec.signature, module=spec.module, func=spec.func,
        spec_md=spec.spec_md.strip(), contract_md=spec.contract_md.strip(),
        regime_md=spec.regime_md.strip(), correctness_md=spec.correctness_md.strip(),
        metric=spec.metric,
        flops_formula=(spec.flops_formula.strip() or spec.flops_src.strip().split("return ")[-1].strip()),
        perf_md=spec.perf_md.strip(), precision_md=spec.precision_md.strip(), faithfulness=FAITHFULNESS))
    (d / "task.toml").write_text(TASK_TOML.format(
        name=spec.name, description=spec.blurb.replace("\n", " ").replace('"', "'"),
        keywords=", ".join(f'"{k}"' for k in (spec.keywords or ["mle", "kernel-generation"])),
        verifier_timeout_sec=spec.verifier_timeout_sec, agent_timeout_sec=spec.agent_timeout_sec,
        memory_mb=spec.memory_mb, gpus=spec.gpus))
    (d / "RUN.md").write_text(RUN_MD.format(name=spec.name, blurb=spec.blurb, gpus=spec.gpus,
                                            module=spec.module, metric=spec.metric))
    for f in SHARED:
        shutil.copy(HERE / "shared" / f, d / "environment" / f)
    return d


if __name__ == "__main__":
    import importlib.util
    path = pathlib.Path(sys.argv[1]).resolve()
    s = importlib.util.spec_from_file_location(path.stem, path)
    mod = importlib.util.module_from_spec(s)
    s.loader.exec_module(mod)                      # importlib (not exec) so specs can use __file__
    out = build(mod.SPEC, out_root=sys.argv[2] if len(sys.argv) > 2 else LANE)
    print("generated", out)
    for p in sorted(out.rglob("*")):
        if p.is_file():
            print("   ", p.relative_to(out))