File size: 27,891 Bytes
0f775e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e597d6
 
 
 
0f775e2
3e597d6
0f775e2
 
3e597d6
 
 
 
 
 
 
 
0f775e2
 
 
 
 
 
3e597d6
 
 
 
 
0f775e2
3e597d6
 
0f775e2
3e597d6
0f775e2
3e597d6
 
 
 
 
 
 
 
0f775e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d31ab5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f775e2
 
 
 
 
 
3e597d6
 
 
 
 
 
 
 
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
"""Generate one megakernel task from a MegaSpec.

Produces the same file layout as _factory/build.py so harbor sees a uniform lane, but the grader is
different: stateful multi-step workload, measured fusion gates, throughput reward.

The generated grader is architecture-agnostic. Everything model-specific lives in the spec's
`model_src`, which must define:

    make_weights(cfg, seed, device)                 -> weights
    make_kv(cfg, batch, prefill_len, max_seq, seed) -> per-step state (may be [] / None)
    <entry_build>(weights, kv, cfg, max_seq_len)    -> handle
    <entry_step>(handle, *args)                     -> output tensor (or tuple of tensors)

and may override the two defaults injected by PRELUDE_SRC:

    make_step_args(cfg, batch, base_pos, seed, n)   -> list of arg tuples, one per step
    compare(got, exp)                               -> float relative error
"""
import pathlib
import shutil
import sys

HERE = pathlib.Path(__file__).resolve().parent
LANE = HERE.parent
sys.path.insert(0, str(HERE))
from model import MODEL_SRC                                                        # noqa: E402

SHARED = ["restrict-network.sh", "CLAUDE.md", "PROCESS_MANAGEMENT.md"]

PREAMBLE = "import torch\nimport torch.nn.functional as F"

# Injected BEFORE model_src, so a model source that defines either name overrides the default.
PRELUDE_SRC = r'''
def make_step_args(cfg, batch, base_pos, seed, n):
    """Arguments passed to each step, after the handle. Default: (token_ids, pos)."""
    g = torch.Generator(device="cuda").manual_seed(seed)
    return [(torch.randint(0, cfg["vocab"], (batch,), device="cuda", generator=g), base_pos + i)
            for i in range(n)]


def compare(got, exp):
    """Relative error (Frobenius) used by the correctness gate. Tuples compare worst-elementwise."""
    if isinstance(exp, (tuple, list)):
        return max(compare(g, e) for g, e in zip(got, exp))
    a, b = got.float(), exp.float()
    return ((a - b).norm() / b.norm().clamp(min=1e-9)).item()
'''

# --------------------------------------------------------------------------------------------------
VERIFY = '''"""{name} verifier — three gates, then an uncapped {metric} SPEED LEADERBOARD.

    reward = 0                if ANY gate fails
    reward = {metric}         otherwise

GATES
  1. correctness      full-output relative error <= {tol} at every compared step
  2. kernels/call     <= {max_kernels} CUDA kernel launches per timed call
  3. dominant share   the largest single kernel is >= {min_dom} of GPU busy time in a call

Gates 2 and 3 are what make this a FUSION task rather than a generic speed task. They are measured,
not inspected: nothing reads your source. CUDA Graphs do not help -- a graph replays the same nodes, so
graphed eager torch still launches the same number of kernels (measured), missing gate 2 by a wide
margin.

Gates 2/3 are measured in a SEPARATE profiled run; the reward comes from a clean unprofiled run, so
profiler overhead never contaminates your score.

A submission whose persistent kernel is launched once in {entry_build}() and driven by flags will show
0 launches/call. That is the ideal design and passes both gates.

ANTI-REPLAY: every timed rep uses fresh state and a fresh argument sequence, and the output of the
last timed rep is validated against the reference for that exact sequence.

GENERATED by _mega_factory/build.py — do not edit here; edit the spec and regenerate.
"""
import importlib.util
import json
import os
import sys
import traceback

{preamble}

REWARD_DIR = "/logs/verifier"
MODULE_PATH = "/app/{module}"
CFG = {cfg!r}
TOL = {tol!r}
BATCH, PREFILL, MAX_SEQ = {batch}, {prefill}, {max_seq}
DECODE_STEPS, CORRECT_STEPS, PROF_STEPS = {decode_steps}, {correct_steps}, {prof_steps}
MAX_KERNELS, MIN_DOM = {max_kernels!r}, {min_dom!r}
WEIGHT_BYTES, FLOOR_US = {weight_bytes}, {floor_us:.1f}
REWARD_WORK, METRIC = {reward_work!r}, "{metric}"

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

{model_src}


def _args(seed, n, base=0):
    return make_step_args(CFG, BATCH, PREFILL + base, seed, n)


def _fresh(seed):
    """Independent weights + state. Built twice from the same seed rather than shared, so a submission
    that repacks or mutates its inputs cannot disturb the reference."""
    return (make_weights(CFG, seed=seed), make_kv(CFG, BATCH, PREFILL, MAX_SEQ, seed=seed))


def _teardown(mod, h):
    fn = getattr(mod, "teardown", None)
    if fn is not None:
        try:
            fn(h)
        except Exception:
            pass


def main():
    details, gates, thru = {{}}, {{}}, 0.0
    try:
        s = importlib.util.spec_from_file_location("submission", MODULE_PATH)
        m = importlib.util.module_from_spec(s)
        s.loader.exec_module(m)

        # ---- gate 1: correctness over CORRECT_STEPS ------------------------------------------------
        W, kv = _fresh(11)
        hs = m.{entry_build}(W, kv, CFG, MAX_SEQ)
        Wr, kvr = _fresh(11)
        hr = {entry_build}(Wr, kvr, CFG, MAX_SEQ)
        worst, bad = 0.0, ""
        for i, a in enumerate(_args(500, CORRECT_STEPS)):
            got = m.{entry_step}(hs, *a)
            exp = {entry_step}(hr, *a)
            e = compare(got, exp)
            worst = max(worst, e)
            if e > TOL:
                bad = f"step {{i}} relerr {{e:.5f}} > {{TOL}}"
                break
        gates["correct"] = not bad
        details["worst_relerr"] = round(worst, 6)
        details["correct_msg"] = bad or f"all {{CORRECT_STEPS}} steps within {{TOL}} (worst {{worst:.5f}})"
        _teardown(m, hs)
        del W, kv, hs, Wr, kvr, hr
        torch.cuda.empty_cache()

        # ---- gates 2+3: profiled run (never timed) -------------------------------------------------
        from torch.profiler import profile, ProfilerActivity
        W, kv = _fresh(12)
        h = m.{entry_build}(W, kv, CFG, MAX_SEQ)
        for a in _args(600, 4):
            m.{entry_step}(h, *a)
        torch.cuda.synchronize()
        pt = _args(601, PROF_STEPS, 4)
        with profile(activities=[ProfilerActivity.CUDA]) as prof:
            for a in pt:
                m.{entry_step}(h, *a)
            torch.cuda.synchronize()
        ka = [k for k in prof.key_averages() if k.self_device_time_total > 0]
        if ka:
            tot = sum(k.self_device_time_total for k in ka)
            per_step = sum(k.count for k in ka) / PROF_STEPS
            dom = max(k.self_device_time_total for k in ka) / max(tot, 1e-9)
            top = max(ka, key=lambda k: k.self_device_time_total).key[:48]
        else:
            # no kernel launched inside a call -> a persistent kernel launched in {entry_build}
            per_step, dom, top = 0.0, 1.0, "<persistent kernel spanning the timed region>"
        gates["kernels_per_step"] = per_step <= MAX_KERNELS
        gates["dominant_share"] = dom >= MIN_DOM
        details.update(kernels_per_step=round(per_step, 2), dominant_share=round(dom, 4),
                       dominant_kernel=top)
        _teardown(m, h)
        del W, kv, h
        torch.cuda.empty_cache()

        # ---- reward: clean unprofiled timing, fresh state per rep ----------------------------------
        best_s, timed_ok = float("inf"), True
        for rep in range(3):
            W, kv = _fresh(20 + rep)
            h = m.{entry_build}(W, kv, CFG, MAX_SEQ)
            seq = _args(900 + rep, DECODE_STEPS)
            for a in seq[:3]:                                    # warm on a throwaway prefix
                m.{entry_step}(h, *a)
            torch.cuda.synchronize()
            W2, kv2 = _fresh(20 + rep)
            h2 = m.{entry_build}(W2, kv2, CFG, MAX_SEQ)
            ev0 = torch.cuda.Event(enable_timing=True)
            ev1 = torch.cuda.Event(enable_timing=True)
            ev0.record()
            for a in seq:
                out = m.{entry_step}(h2, *a)
            ev1.record()
            torch.cuda.synchronize()
            best_s = min(best_s, ev0.elapsed_time(ev1) / 1e3)
            if rep == 2:                                          # validate the LAST timed rep
                Wr, kvr = _fresh(20 + rep)
                hr = {entry_build}(Wr, kvr, CFG, MAX_SEQ)
                for a in seq:
                    exp = {entry_step}(hr, *a)
                timed_ok = compare(out, exp) <= TOL
                del Wr, kvr, hr
            _teardown(m, h)
            _teardown(m, h2)
            del W, kv, h, W2, kv2, h2
            torch.cuda.empty_cache()
        gates["timed_output_valid"] = timed_ok
        thru = (REWARD_WORK * DECODE_STEPS) / best_s if best_s > 0 else 0.0
        details.update(throughput=round(thru, 2), metric=METRIC,
                       us_per_step=round(best_s / DECODE_STEPS * 1e6, 1),
                       floor_us=FLOOR_US,
                       x_above_floor=round((best_s / DECODE_STEPS * 1e6) / FLOOR_US, 2))
    except Exception as e:
        details["error"] = f"{{e.__class__.__name__}}: {{e}}"[:220]
        details["trace"] = traceback.format_exc()[-900:]

    ok = bool(gates) and all(gates.values())
    reward = round(thru, 3) if ok else 0.0
    details["gates"] = gates
    os.makedirs(REWARD_DIR, exist_ok=True)
    json.dump({{"reward": reward, "correct": 1.0 if ok else 0.0,
               "throughput": round(thru, 3), "metric": "{metric} (uncapped)"}},
              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 ok else 0.0, "| gates:", gates)


main()
'''

# --------------------------------------------------------------------------------------------------
MEASURE = '''"""Self-assessment — your three gates and your {metric}, same method as the grader.

Run:  python3 /app/measure.py
This does NOT set your score; it exists so you can iterate without guessing.
"""
import importlib.util
import sys

{preamble}

CFG = {cfg!r}
TOL = {tol!r}
BATCH, PREFILL, MAX_SEQ = {batch}, {prefill}, {max_seq}
DECODE_STEPS, CORRECT_STEPS, PROF_STEPS = {decode_steps}, {correct_steps}, {prof_steps}
MAX_KERNELS, MIN_DOM = {max_kernels!r}, {min_dom!r}
FLOOR_US, REWARD_WORK = {floor_us:.1f}, {reward_work!r}

sys.path.insert(0, "/app")
{model_src}


def main():
    s = importlib.util.spec_from_file_location("sub", "/app/{module}")
    m = importlib.util.module_from_spec(s)
    s.loader.exec_module(m)
    args = lambda seed, n, base=0: make_step_args(CFG, BATCH, PREFILL + base, seed, n)

    W = make_weights(CFG, seed=11); kv = make_kv(CFG, BATCH, PREFILL, MAX_SEQ, seed=11)
    Wr = make_weights(CFG, seed=11); kvr = make_kv(CFG, BATCH, PREFILL, MAX_SEQ, seed=11)
    hs, hr = m.{entry_build}(W, kv, CFG, MAX_SEQ), {entry_build}(Wr, kvr, CFG, MAX_SEQ)
    worst = 0.0
    for a in args(500, CORRECT_STEPS):
        worst = max(worst, compare(m.{entry_step}(hs, *a), {entry_step}(hr, *a)))
    print(f"gate 1 correctness : worst relerr {{worst:.5f}}  (limit {{TOL}})  "
          f"{{'PASS' if worst <= TOL else 'FAIL'}}")

    from torch.profiler import profile, ProfilerActivity
    for a in args(600, 4, CORRECT_STEPS):
        m.{entry_step}(hs, *a)
    torch.cuda.synchronize()
    with profile(activities=[ProfilerActivity.CUDA]) as prof:
        for a in args(601, PROF_STEPS, CORRECT_STEPS + 4):
            m.{entry_step}(hs, *a)
        torch.cuda.synchronize()
    ka = [k for k in prof.key_averages() if k.self_device_time_total > 0]
    if ka:
        tot = sum(k.self_device_time_total for k in ka)
        per_step = sum(k.count for k in ka) / PROF_STEPS
        dom = max(k.self_device_time_total for k in ka) / max(tot, 1e-9)
    else:
        per_step, dom = 0.0, 1.0
    print(f"gate 2 kernels/call: {{per_step:.1f}}  (limit {{MAX_KERNELS}})  "
          f"{{'PASS' if per_step <= MAX_KERNELS else 'FAIL'}}")
    print(f"gate 3 dominant    : {{dom:.3f}}  (limit {{MIN_DOM}})  "
          f"{{'PASS' if dom >= MIN_DOM else 'FAIL'}}")

    seq = args(900, DECODE_STEPS)
    W2 = make_weights(CFG, seed=20); kv2 = make_kv(CFG, BATCH, PREFILL, MAX_SEQ, seed=20)
    h2 = m.{entry_build}(W2, kv2, CFG, MAX_SEQ)
    for a in seq[:3]:
        m.{entry_step}(h2, *a)
    torch.cuda.synchronize()
    e0, e1 = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
    e0.record()
    for a in seq:
        m.{entry_step}(h2, *a)
    e1.record()
    torch.cuda.synchronize()
    sec = e0.elapsed_time(e1) / 1e3
    us = sec / DECODE_STEPS * 1e6
    print(f"\\nthroughput         : {{REWARD_WORK*DECODE_STEPS/sec:.1f}} {metric}   "
          f"({{us:.0f}} us/call, {{us/FLOOR_US:.1f}}x the {{FLOOR_US:.0f}}us bandwidth floor)")


main()
'''

# --------------------------------------------------------------------------------------------------
STUB = '''"""YOUR SUBMISSION. {stub_head}

Two entry points. `{entry_build}` is UNTIMED — do setup there (repack weights, allocate scratch, launch
a persistent kernel). `{entry_step}` is TIMED and is what the gates measure.

Optionally define `teardown(handle)`; the grader calls it if present, so a persistent daemon can be
stopped cleanly.
"""
import torch
import torch.nn.functional as F


def {entry_build}(weights, kv_cache, cfg, max_seq_len):
    """UNTIMED setup. Return any handle you like — the grader only passes it back to {entry_step}.

    {arg_doc}
    cfg       : the architecture dict
    """
    raise NotImplementedError("implement {entry_build}")


def {entry_step}({step_sig}):
    """TIMED. {step_doc}"""
    raise NotImplementedError("implement {entry_step}")
'''

# --------------------------------------------------------------------------------------------------
DOCKERFILE = '''# {title}
# {blurb_wrapped}
#
# Graded on 1 GPU by three gates (correctness, kernels/call, dominant-kernel share) and rewarded with
# an UNCAPPED {metric} number. Offline: no internet at run time, and only the permitted toolchain is
# installed — there is no flashinfer / vllm / flash-attn / cuBLASLt-fused-model to fall back on.
FROM {base_image}

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
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
RUN rm -rf /var/lib/apt/lists/* /etc/apt/sources.list /etc/apt/sources.list.d
WORKDIR /app

COPY reference.py /app/reference.py
COPY measure.py /app/measure.py
COPY {module} /app/{module}
COPY restrict-network.sh /app/restrict-network.sh
RUN chmod +x /app/restrict-network.sh
COPY CLAUDE.md PROCESS_MANAGEMENT.md /app/
'''

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]
'''

INSTRUCTION = '''# {title}

{intro_md}

Edit **`/app/{module}`**. Two entry points:

```python
def {entry_build}(weights, kv_cache, cfg, max_seq_len) -> handle     # UNTIMED setup
def {entry_step}({step_sig}) -> {step_ret}   # TIMED
def teardown(handle)                                     # OPTIONAL
```

{spec_md}

## The contract

{contract_md}

## Grading: three gates, then an uncapped speed leaderboard

| gate | limit | how it is measured |
|------|-------|--------------------|
| 1. correctness | full-output relative error <= `{tol}` | vs an embedded private copy of the reference |
| 2. kernels / call | <= **{max_kernels}** | CUDA kernel launches in a profiled timed call |
| 3. dominant share | >= **{min_dom}** | largest single kernel's fraction of GPU busy time |

**reward = {metric}, uncapped. Any gate failing scores 0.**

{gates_md}

Nothing reads your source code. Gates 2 and 3 are *measured* — they are properties of how your code
actually executes. Two consequences worth internalising:

* **CUDA Graphs will not get you past gate 2.** A graph replays the same nodes; it removes launch
  overhead, not kernels.{unfused_note}
* **A persistent kernel launched once in `{entry_build}` and driven by flags shows 0 launches/call.**
  That is the ideal design and passes gates 2 and 3 outright.

Gates 2/3 are measured in a separate profiled run; your reward comes from a clean unprofiled run, so
profiling overhead never costs you score.

{regime_md}

## Toolchain

**Write this in CUDA C++ if you can.** A megakernel is exactly the case where you want direct control
over the grid, shared memory, async copies, and the device-wide barrier, and that is easiest to express
in CUDA. `nvcc` and the full CUDA toolkit are installed; build with `torch.utils.cpp_extension` (JIT or
ahead-of-time) or drive `nvcc` yourself. CUTLASS and the CuTe DSL are available.

**Triton is also acceptable** — a grid-wide barrier built from `tl.atomic_add` / `tl.atomic_cas` with a
spin loop does work here, provided your grid stays co-resident (a grid larger than what fits deadlocks
the blocks already spinning). If you find Triton expressive enough for the fusion you want, use it.

**The exact GPU is deliberately not stated — query it.** You are guaranteed compute capability
**sm≥90**, so fp8, TMA and wgmma-class instructions exist; nothing beyond that is promised. The reward
is an absolute {metric} number, and the same submission is graded on whatever device it
lands on. A grid size, tile shape or bandwidth constant hardcoded to a part you assumed is just slower.

```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.shared_memory_per_block_optin   # opt-in dynamic smem, the number that matters for big tiles
p.total_memory, p.regs_per_multiprocessor, p.max_threads_per_multi_processor
```

Measure achieved HBM bandwidth with a large stream-copy rather than trusting a datasheet figure — every
roofline quoted below is `bytes moved / (that measured bandwidth)`.

What is **not** available, by construction rather than by policy: there is no internet at run time and
no flashinfer, vLLM, TensorRT-LLM, flash-attn, or any pre-fused whole-model inference kernel installed.
`torch` is present and you may use it for setup and for anything with no efficient direct alternative,
but note that a torch-op implementation of `{entry_step}` cannot pass gate 2 no matter how it is wrapped.

**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) rather than spending your budget fighting it. `ncu --version`
succeeds either way; it never touches a counter. Kernel *replay* also breaks a persistent
grid-synchronizing kernel — if you do profile one, use `ncu --replay-mode application`.

## Correctness

{correctness_md}

## Precision

{precision_md}

## Where the performance comes from

{perf_md}

## Self-assessment

`python3 /app/measure.py` reports all three gates and your {metric} using the grader's method. Use it
freely — it does not set your score.

## Faithfulness

{faithfulness}
'''

FAITHFULNESS = '''Your kernel must actually compute the reference computation. Specifically:

* Do **not** skip work, shrink a dimension, or approximate a reduction that the reference performs
  exactly.
* Do **not** cache outputs across calls and replay them — every timed rep uses fresh state and a fresh
  argument sequence, and the output of the last timed rep is validated.
* Do **not** mutate the reference's inputs to make the comparison easier; the grader builds its own
  independent copy of every fixture from the same seed.

You may repack, requantise, or re-layout the weights inside `{entry_build}` — that is untimed setup and
is exactly what a real serving stack does. You may allocate whatever scratch you need there too.
'''

E1_FAITHFULNESS = '''Your kernel must actually compute the model. Specifically:

* Do **not** skip layers, shrink the vocabulary, or approximate the attention over the KV cache.
* Do **not** cache logits across steps and replay them — every timed rep uses a fresh KV cache and a
  fresh token sequence, and the final logits of the last timed rep are validated.
* Do **not** mutate the reference's inputs to make the comparison easier; the grader builds its own
  independent copy of the weights and KV from the same seed.

You may repack, requantise, or re-layout the weights inside `{entry_build}` — that is untimed setup and
is exactly what a real serving stack does. You may allocate whatever scratch you need there too.
'''

E1_INTRO = '''You are writing a **megakernel**: the entire decode step of a transformer, fused into
(essentially) one persistent GPU kernel. This is not a "make it fast" task with a fusion hint — fusion
is **gated**.'''

E1_GATES = '''Gate 2 is set at a whole-model granularity on purpose: a decode step of this model is
~40 fusable operations per layer, and an unfused implementation launches hundreds of kernels per step.
Allowing a handful of launches leaves room for a token copy, a flag reset, or a trivial epilogue
without leaving room for a per-op implementation. Gate 3 then requires that whatever you do launch is
*one* kernel doing essentially all of the work, so the count cannot be gamed by batching the model into
a few large-but-still-unfused calls.'''

RUN_MD = '''# {name}

{blurb}

* **GPUs**: {gpus}
* **Edit**: `/app/{module}`
* **Reward**: {metric}, uncapped, gated on correctness + kernels/call + dominant-kernel share

```bash
docker build -t {name} environment
docker run --rm --gpus device=0 -v $PWD/tests:/tests:ro {name} bash /tests/test.sh
```
'''


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)

    src = PRELUDE_SRC.strip("\n") + "\n\n\n" + (spec.model_src or MODEL_SRC).strip("\n")
    common = dict(name=spec.name, module=spec.module, cfg=spec.cfg, tol=spec.tol,
                  batch=spec.batch, prefill=spec.prefill_len, max_seq=spec.max_seq,
                  decode_steps=spec.decode_steps, correct_steps=spec.correct_steps,
                  prof_steps=spec.prof_steps, max_kernels=spec.max_kernels_per_step,
                  min_dom=spec.min_dominant_share, preamble=PREAMBLE, model_src=src,
                  entry_build=spec.entry_build, entry_step=spec.entry_step,
                  metric=spec.reward_metric, reward_work=spec.work_per_step(),
                  weight_bytes=int(spec.total_bytes()), floor_us=spec.floor_us())

    (d / "environment" / "reference.py").write_text(
        f'"""Reference implementation — the CORRECTNESS SPEC for `{spec.name}`.\n\n'
        f"Correct, deliberately unfused, and slow. Its speed has no bearing on your score, which is an\n"
        f"absolute {spec.reward_metric} number. GENERATED by _mega_factory/build.py.\n"
        f'"""\n{PREAMBLE}\n\n{src}\n')
    (d / "tests" / "verify_env.py").write_text(VERIFY.format(**common))
    (d / "tests" / "test.sh").write_text(
        "#!/bin/bash\n# GENERATED by _mega_factory/build.py.\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(**common))
    (d / "environment" / spec.module).write_text(STUB.format(
        entry_build=spec.entry_build, entry_step=spec.entry_step, step_sig=spec.step_sig,
        step_doc=spec.step_doc, arg_doc=spec.arg_doc,
        stub_head=("Fuse the whole decode step into a megakernel." if spec.family == "e1"
                   else "Fuse this primitive into a single persistent kernel.")))
    (d / "environment" / "Dockerfile").write_text(DOCKERFILE.format(
        title=spec.title, blurb_wrapped=spec.blurb.replace("\n", "\n# "), metric=spec.reward_metric,
        base_image=spec.base_image, module=spec.module, pip_extra=spec.pip_extra))
    (d / "instruction.md").write_text(INSTRUCTION.format(
        title=spec.title, module=spec.module, tol=spec.tol,
        max_kernels=spec.max_kernels_per_step, min_dom=spec.min_dominant_share,
        entry_build=spec.entry_build, entry_step=spec.entry_step, step_sig=spec.step_sig,
        metric=spec.reward_metric, step_ret=spec.step_ret,
        unfused_note=(f" Eager torch here launches ~{spec.unfused_kernels} kernels/call — off by "
                      f"~{spec.unfused_kernels / max(spec.max_kernels_per_step, 1):.0f}x."
                      if spec.unfused_kernels else ""),
        intro_md=(spec.intro_md or E1_INTRO).strip(),
        spec_md=spec.spec_md.strip(), contract_md=spec.contract_md.strip(),
        gates_md=(spec.gates_md or (E1_GATES if spec.family == "e1" else "")).strip(),
        regime_md=spec.regime_md.strip(), correctness_md=spec.correctness_md.strip(),
        precision_md=spec.precision_md.strip(), perf_md=spec.perf_md.strip(),
        faithfulness=(spec.faithfulness_md
                      or (E1_FAITHFULNESS if spec.family == "e1" else FAITHFULNESS)).format(
            entry_build=spec.entry_build).strip()))
    (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.reward_metric))
    for f in SHARED:
        shutil.copy(LANE / "_factory" / "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)
    out = build(mod.SPEC, out_root=sys.argv[2] if len(sys.argv) > 2 else LANE)
    print(f"generated {out}  floor={mod.SPEC.floor_us():.0f}us  metric={mod.SPEC.reward_metric}")