Elfsong commited on
Commit
1276a5c
·
verified ·
1 Parent(s): 3a62c2e

KernelBench-M artifact: rules, substrates, witnesses, pipeline, summaries

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. LEVEL3_BRIEF.md +59 -0
  2. README.md +76 -0
  3. SPEC.md +69 -0
  4. WITNESS_BRIEF.md +72 -0
  5. gate_report.json +102 -0
  6. holdout.json +10 -0
  7. invalid_suites.json +54 -0
  8. ladder/BRIEF_R1.md +27 -0
  9. ladder/BRIEF_R3.md +38 -0
  10. ladder_summary.json +1 -0
  11. mechanism_curves.json +154 -0
  12. miss_patterns.json +157 -0
  13. pipeline/adjudicate.py +207 -0
  14. pipeline/analyze_cover.py +119 -0
  15. pipeline/analyze_holdout.py +92 -0
  16. pipeline/audit_matrix.py +314 -0
  17. pipeline/candidates_loader.py +49 -0
  18. pipeline/competitor_suites.py +93 -0
  19. pipeline/coverage_report.py +85 -0
  20. pipeline/driver.py +113 -0
  21. pipeline/eval_kernel.py +177 -0
  22. pipeline/find_substrate.py +8 -0
  23. pipeline/forkpool.py +73 -0
  24. pipeline/full_matrix.py +180 -0
  25. pipeline/gate_candidates.py +85 -0
  26. pipeline/kernels_def.py +437 -0
  27. pipeline/mechanism_curves.py +99 -0
  28. pipeline/mutator.py +288 -0
  29. pipeline/nvrtc_tce.py +161 -0
  30. pipeline/problems_batch2.py +799 -0
  31. pipeline/problems_ext.py +672 -0
  32. pipeline/recheck_nowitness.py +220 -0
  33. pipeline/sanitizer_probe.py +29 -0
  34. pipeline/screen_mutants.py +534 -0
  35. pipeline/suite_filter.py +70 -0
  36. pipeline/validate_ext.py +56 -0
  37. rules/BRIEF.md +79 -0
  38. rules/BRIEF3.md +86 -0
  39. rules/fine_rules.py +144 -0
  40. rules/mined_rules.py +142 -0
  41. rules/structural_rules.py +124 -0
  42. substrates/candidate_L2p10_convtranspose2d_maxpoo.py +206 -0
  43. substrates/candidate_L2p11_convtranspose2d_batchn.py +320 -0
  44. substrates/candidate_L2p12_gemm_multiply_leakyrel.py +159 -0
  45. substrates/candidate_L2p13_convtranspose3d_mean_a.py +260 -0
  46. substrates/candidate_L2p14_gemm_divide_sum_scalin.py +156 -0
  47. substrates/candidate_L2p15_convtranspose3d_batchn.py +298 -0
  48. substrates/candidate_L2p16_convtranspose2d_mish_a.py +196 -0
  49. substrates/candidate_L2p17_conv2d_instancenorm_di.py +215 -0
  50. substrates/candidate_L2p18_matmul_sum_max_avgpool.py +170 -0
LEVEL3_BRIEF.md ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Brief: level-3 substrates (full architectures, multi-kernel)
2
+
3
+ Level-3 KernelBench problems are whole networks. Their substrate is a PIPELINE
4
+ of kernels — one `__global__` per layer — so that a mutation lands in a
5
+ specific layer and we can measure how far a fault propagates through depth.
6
+
7
+ Read `substrates/SPEC.md` first for the general contract, then the differences
8
+ below. Read `problems_batch2.py` for the CUDA style, and at least two accepted
9
+ substrates from `substrates/accepted/`.
10
+
11
+ ## What changes vs a level-1/2 substrate
12
+
13
+ 1. `cuda` holds SEVERAL `__global__` kernels, one per layer of the network
14
+ (e.g. `mlp_gemm_relu_kernel`, `mlp_gemm_kernel`). Name them so the layer is
15
+ identifiable.
16
+ 2. `kernel_name` is a LIST of those symbol names, in pipeline order.
17
+ 3. `launch` returns a DICT describing the sequence instead of a single tuple:
18
+
19
+ ```python
20
+ def launch(inputs, torch):
21
+ x = inputs[0]
22
+ ...
23
+ bufs = [torch.zeros(...), ...] # intermediate activations
24
+ seq = [
25
+ # (kernel_name, grid3, block3, [tensor args in order], [(ctype, scalar), ...])
26
+ ("layer0_kernel", (gx, gy, 1), (32, 32, 1), [x, w0, b0, bufs[0]],
27
+ [(ctypes.c_int, M), (ctypes.c_int, K), (ctypes.c_int, N)]),
28
+ ("layer1_kernel", ..., [bufs[0], w1, b1, out], [...]),
29
+ ]
30
+ return {"seq": seq, "out": out}
31
+ ```
32
+
33
+ Tensor arguments are passed as data pointers in the order listed; scalars
34
+ follow. Allocate intermediates inside `launch`.
35
+
36
+ 4. WEIGHTS: the reference `Model` owns nn.Parameters. Create them ONCE with a
37
+ fixed seed inside the substrate module (module-level, lazily on first use),
38
+ and have `ref` use THE SAME tensors, so reference and kernel see identical
39
+ weights. Put them on the input's device.
40
+
41
+ 5. `ref` must reproduce the KernelBench `Model.forward` exactly, using those
42
+ same weights (e.g. `torch.nn.functional.linear(x, W0, b0).relu()` ...).
43
+
44
+ 6. Suites: `T0_original` must reproduce the problem's `get_inputs()`; add 2-3
45
+ targeted suites. Keep the legitimate-variance ceiling in mind: prefer
46
+ same-sign large values over signed ones.
47
+
48
+ ## Performance does not matter
49
+
50
+ Naive kernels are fine (one thread per output element, sequential loops). What
51
+ matters is: correct, readable, and rich in mutation sites (explicit bounds
52
+ guards, ceil-division, distinct `__syncthreads()` where relevant).
53
+
54
+ ## Deliverable
55
+
56
+ `substrates/candidate_L3p<N>_<short>.py` with a `register(K, torch, ctypes)`
57
+ function exactly as in SPEC.md, plus `kernel_name` as a list and the dict-style
58
+ `launch` above. Import-safe, no GPU work at import time, do not modify other
59
+ files.
README.md ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # KernelBench-M
2
+
3
+ The measurement artifact for *Measuring the Checker: Mutation Analysis for
4
+ GPU-Kernel Benchmark Oracles*: the mutation operators, the verified CUDA
5
+ substrates they mutate, the kill witnesses, and the pipeline that produced
6
+ every number in the paper.
7
+
8
+ ## Layout
9
+
10
+ ```
11
+ rules/ 124 mutation rules, six families (mutator.py loads all of them)
12
+ substrates/ 208 gate-verified CUDA implementations, one per KernelBench
13
+ problem: the mutation targets. Never used as oracle.
14
+ witnesses/ per-problem kill records: for every mutant, its rule, family,
15
+ mutated site, whether the official protocol kills it, and — when
16
+ it survives — a suite that does
17
+ pipeline/ the measurement code (screening, kill matrix, audit, set cover)
18
+ summary.json per-problem mutant / witnessed / official-kill counts
19
+ ```
20
+
21
+ Supporting records: `mechanism_curves.json` (Fig. 2b–c), `holdout.json`
22
+ (dev/test split), `ladder_summary.json` (knowledge ladder),
23
+ `gate_report.json` (substrate admission), `invalid_suites.json` (suites
24
+ rejected for crossing the validity ceiling).
25
+
26
+ ## What a substrate is, and is not
27
+
28
+ KernelBench ships PyTorch references whose GPU execution bottoms out in closed
29
+ cuDNN/cuBLAS binaries, so there is no source to mutate. A *substrate* is a
30
+ correct CUDA implementation of the same computation, used **only** as a
31
+ mutation target. The oracle stays the benchmark's own PyTorch reference. Each
32
+ substrate is admitted by `pipeline/gate_candidates.py`, which compares it
33
+ against that reference on every suite before it may enter the pool
34
+ (`gate_report.json` records admissions and rejections).
35
+
36
+ ## Witness format
37
+
38
+ ```json
39
+ "softmax:barrier-drop:3": {
40
+ "rule": "barrier-drop", "family": "sync",
41
+ "site": "__syncthreads();",
42
+ "cls": "high_value",
43
+ "killed_by_official": false,
44
+ "witness": "T2_misaligned_batch"
45
+ }
46
+ ```
47
+
48
+ `cls` is `killed_by_T0` (the official inputs detect it), `high_value` (survives
49
+ the official inputs, a targeted input detects it), or `no_witness` (nothing we
50
+ have detects it — an equivalence or oracle-blindness candidate, excluded from
51
+ every denominator in the paper).
52
+
53
+ ## Reproducing
54
+
55
+ Requires an NVIDIA GPU with CUDA 12.x and PyTorch. From `pipeline/`:
56
+
57
+ ```bash
58
+ python screen_mutants.py # generate, filter, and screen mutants
59
+ python full_matrix.py # kill matrix over all suites
60
+ python audit_matrix.py # score competing protocols (§5)
61
+ python analyze_cover.py # set-cover suite synthesis (§6)
62
+ python analyze_holdout.py # dev/test holdout (§6)
63
+ ```
64
+
65
+ Each stage writes append-only JSONL journals and resumes from them, so a
66
+ crashed or preempted run can simply be restarted. `SHARD_ID`/`SHARD_N` split
67
+ problems across GPUs; `STEAL=1` lets an idle worker pick up unclaimed problems.
68
+
69
+ ## Caveats
70
+
71
+ Mutation score is adequacy relative to this fault model, not absolute
72
+ correctness: these operators cannot express faults living in structures the
73
+ substrates do not contain (tensor-core paths, double-buffered pipelines), nor
74
+ multi-site interactions. The artifact supports comparative claims between
75
+ protocols and existence claims about specific faults. It cannot certify that a
76
+ kernel passing these suites is correct.
SPEC.md ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Substrate candidate spec (for automated kernel authors)
2
+
3
+ A substrate is a CORRECT CUDA implementation of one KernelBench level1 problem,
4
+ used as the mutation target. It is NOT the correctness oracle (the official
5
+ PyTorch reference is). Every candidate must pass an automated gate comparing it
6
+ against the official reference on multiple input suites before admission.
7
+
8
+ ## Deliverable
9
+
10
+ One Python file: `substrates/candidate_<name>.py` (snake_case short name).
11
+ It must be import-safe (no GPU work at import time) and define exactly:
12
+
13
+ ```python
14
+ def register(K, torch, ctypes):
15
+ K.PROBLEMS["<name>"] = dict(
16
+ kb_file="<original KernelBench filename>",
17
+ cuda=CUDA_SOURCE, # device-only source, see rules below
18
+ kernel_name="<kernel symbol>",
19
+ ref=<callable>, # torch reference, MUST match the KB Model's
20
+ # forward() semantics exactly (params from
21
+ # get_init_inputs() defaults)
22
+ launch=<callable>, # (inputs, torch) -> (out_tensor, grid3,
23
+ # block3, [(ctypes_type, value), ...])
24
+ suites=<callable>, # () -> [(name, n_trials, builder)]
25
+ probe=<callable>, # (torch) -> [(name, [small cpu tensors])]
26
+ )
27
+ ```
28
+
29
+ ## CUDA source rules
30
+
31
+ - Device code ONLY: `__global__` kernel(s) + `#include <cuda_fp16.h>` (and
32
+ `<math_constants.h>` if needed). NO torch headers, NO host wrapper.
33
+ It is compiled with NVRTC; the launch config lives in the Python `launch`.
34
+ - fp32 in/out. Use `long long` for any index that can exceed 2^31.
35
+ - One thread-block pattern from the proven set when applicable:
36
+ elementwise 1D grid; block-per-row with 256-thread shared-memory reduction;
37
+ 32x32 shared-memory tiles for matmul; column-thread + row-loop for
38
+ dim-1 reductions. Look at ../problems_batch2.py for working examples of all
39
+ four patterns, including suites/probe conventions.
40
+ - Structure the source so mutation sites are visible: keep bounds guards as
41
+ single-line `if (...) { ... }` or `if (...) return;`, use ceil-division
42
+ `(x + K - 1) / K`, label repeated `__syncthreads();` with distinct trailing
43
+ comments (e.g. `// sync-after-load`).
44
+
45
+ ## Suites rules
46
+
47
+ - `T0_original`: EXACTLY the shapes/distribution of the problem's
48
+ `get_inputs()` (5 trials, seed `1000 + t`).
49
+ - Plus 2-3 targeted suites: signed values, misaligned shapes (dims not
50
+ divisible by 32/256), and a structure-specific stressor (spike/large values)
51
+ where meaningful. Seed every builder deterministically.
52
+ - CRITICAL: no suite may false-kill a correct implementation. Avoid
53
+ large-magnitude SIGNED values feeding long accumulations (catastrophic
54
+ cancellation exceeds the 1e-2 tolerance between two legitimate fp32
55
+ implementations); use positive-only values for large-magnitude suites.
56
+
57
+ ## Probe rules
58
+
59
+ Tiny CPU tensors (<1 MB), 2 entries: one aligned T0-like, one misaligned.
60
+
61
+ ## Semantics rules
62
+
63
+ - Read the KernelBench problem file CAREFULLY: match forward() exactly
64
+ (e.g. L1Norm divides by mean(|x|), NOT sum; reductions may or may not
65
+ keepdim; losses reduce to a scalar with 'mean').
66
+ - Scalar outputs: return a 0-dim or shape-(1,) tensor from launch's out and
67
+ make ref produce the matching shape.
68
+ - Integer-output ops (argmax/argmin): out dtype int64 in launch, ref returns
69
+ the indices tensor; comparison is exact.
WITNESS_BRIEF.md ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Brief: write killer inputs for surviving mutants
2
+
3
+ ## Situation
4
+
5
+ For your assigned task, a set of MUTANTS (deliberately faulty variants of the
6
+ task's correct CUDA kernel) survives every test input we currently have — the
7
+ benchmark's original inputs AND our targeted suites. Your job is to design
8
+ additional test inputs that expose them.
9
+
10
+ The correctness check is fixed and is NOT yours to change:
11
+ torch.allclose(reference_output, kernel_output, atol=1e-2, rtol=1e-2)
12
+ where reference_output comes from the official PyTorch implementation.
13
+
14
+ ## Hard constraint (violating this fails the work)
15
+
16
+ A new input MUST NOT make the CORRECT kernel fail the check. Two legitimate
17
+ fp32 implementations differ by accumulation order; if you push magnitudes too
18
+ far, cancellation makes the correct kernel itself exceed the tolerance and the
19
+ input is worthless (it would reject valid submissions).
20
+
21
+ Measured ceiling on a K=8192 reduction:
22
+ signed values (randn * s): safe to s≈100, FALSE-KILLS at s≈300
23
+ positive values (|randn|* s): safe to s≈3000 and beyond
24
+ So: to test large magnitudes, use SAME-SIGN large values, not signed ones.
25
+
26
+ ## Why mutants survive, and what input defeats each family
27
+
28
+ - `loop-bound-minus1`, `loop-start-1`, `strided-tail-drop`: the kernel skips
29
+ the first/last element of a loop. Under uniform random input, one missing
30
+ term out of thousands is far below tolerance. KILLER: make the skipped
31
+ position carry almost all the mass — e.g. all entries tiny (1e-3) except
32
+ the first/last of the reduced axis set to a large positive value; or use a
33
+ reduction length short enough that one term matters.
34
+ - `sync-remove`, `sync2syncwarp`: a barrier is gone, so a thread may read a
35
+ shared-memory slot before its partner wrote it. With uniform values the
36
+ stale and fresh values are close, so the error hides. KILLER: make adjacent
37
+ lanes carry wildly different magnitudes (e.g. alternate 1e-4 and 1e3 across
38
+ the reduced axis), so reading the wrong one is unmistakable.
39
+ - `store-fp16`, precision-family: output rounded through fp16 (rel. error
40
+ ~1e-3). Hidden while |output| is small. KILLER: drive OUTPUT magnitude up
41
+ (positive-only large inputs), so rtol*|out| still bounds but the absolute
42
+ fp16 rounding error exceeds atol — or make outputs land near fp16 subnormal
43
+ or above 65504 (fp16 overflow -> inf).
44
+ - `lt2le`, `ge2gt`, guard mutations: off-by-one at the boundary. KILLER: use
45
+ a MISALIGNED shape (dimension not divisible by 32/256) so a partial block
46
+ exists, and place extreme values in the final positions.
47
+ - `mul2div`, `mul2plus` on index arithmetic: wrong element read. Under a
48
+ smooth random tensor neighbouring values are similar. KILLER: make the
49
+ tensor's value depend sharply on position (e.g. value = row*1000 + col),
50
+ so any index error yields a wildly wrong number.
51
+ - tie-breaking / sentinel families: ties have probability zero under
52
+ continuous random input. KILLER: inputs with DUPLICATE values, all-negative
53
+ rows, or NaN/Inf entries where the reference has defined behaviour.
54
+
55
+ ## Deliverable
56
+
57
+ Edit ONLY the `suites` function of the task's substrate file (path given in
58
+ your prompt). Keep `T0_original` EXACTLY as it is. Append 2-4 new suites,
59
+ each `(name, 1, builder)` with a deterministic seed, targeting the mutant
60
+ families listed in your prompt. Name them descriptively, e.g.
61
+ `T5_tail_mass_spike`, `T6_alternating_magnitude`, `T7_positional_ramp`.
62
+
63
+ Rules:
64
+ - Keep tensor shapes at or below the original problem's element count (memory).
65
+ - Same dtype and rank as T0; shapes may be misaligned.
66
+ - No NaN/Inf unless the reference implementation defines behaviour for them.
67
+ - Do not modify the CUDA source, ref, launch, or probe.
68
+ - The file must remain import-safe; do not run GPU code.
69
+
70
+ Think about what the FUSED chain does end-to-end: a value that is extreme at
71
+ the input may be squashed by a sigmoid/softmax later, making the fault
72
+ invisible again. Choose inputs whose extremeness SURVIVES to the output.
gate_report.json ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "problem": "L2p100_convtranspose3d_clamp",
4
+ "admitted": true,
5
+ "detail": "ok"
6
+ },
7
+ {
8
+ "problem": "L2p10_convtranspose2d_maxpoo",
9
+ "admitted": true,
10
+ "detail": "ok"
11
+ },
12
+ {
13
+ "problem": "L2p26_convtranspose3d_add_hardswish",
14
+ "admitted": true,
15
+ "detail": "ok"
16
+ },
17
+ {
18
+ "problem": "L2p60_convtranspose3d_swish",
19
+ "admitted": true,
20
+ "detail": "ok"
21
+ },
22
+ {
23
+ "problem": "L2p77_convtranspose3d_scale",
24
+ "admitted": true,
25
+ "detail": "ok"
26
+ },
27
+ {
28
+ "problem": "L2p7_conv3d_relu_leakyrelu",
29
+ "admitted": true,
30
+ "detail": "ok"
31
+ },
32
+ {
33
+ "problem": "L2p92_conv2d_groupnorm_tanh",
34
+ "admitted": true,
35
+ "detail": "ok"
36
+ },
37
+ {
38
+ "problem": "L2p94_gemm_biasadd_hardtanh",
39
+ "admitted": true,
40
+ "detail": "ok"
41
+ },
42
+ {
43
+ "problem": "L2p95_matmul_add_swish_tanh",
44
+ "admitted": true,
45
+ "detail": "ok"
46
+ },
47
+ {
48
+ "problem": "L2p9_matmul_subtract_multiply_relu",
49
+ "admitted": true,
50
+ "detail": "ok"
51
+ },
52
+ {
53
+ "problem": "L3p20_mobilenetv2",
54
+ "admitted": false,
55
+ "detail": "T3_positive_spikes/t0: value max_diff=0.01602"
56
+ },
57
+ {
58
+ "problem": "L3p24_efficientnetb2",
59
+ "admitted": false,
60
+ "detail": "T0_original/t0: value max_diff=1.422"
61
+ },
62
+ {
63
+ "problem": "L3p25_shufflenetunit",
64
+ "admitted": true,
65
+ "detail": "ok"
66
+ },
67
+ {
68
+ "problem": "L3p43_attention",
69
+ "admitted": true,
70
+ "detail": "ok"
71
+ },
72
+ {
73
+ "problem": "L3p45_unetsoftmax",
74
+ "admitted": false,
75
+ "detail": "T0_original/t0: value max_diff=0.3798"
76
+ },
77
+ {
78
+ "problem": "L3p48_mamba2returny",
79
+ "admitted": false,
80
+ "detail": "T0_original/t0: value max_diff=8.576e+13"
81
+ },
82
+ {
83
+ "problem": "L3p49_mamba2returnfinalsta",
84
+ "admitted": true,
85
+ "detail": "ok"
86
+ },
87
+ {
88
+ "problem": "batched_matrix_multiplication",
89
+ "admitted": true,
90
+ "detail": "ok"
91
+ },
92
+ {
93
+ "problem": "matmul_with_large_k_dimension",
94
+ "admitted": true,
95
+ "detail": "ok"
96
+ },
97
+ {
98
+ "problem": "matmul_with_small_k_dimension",
99
+ "admitted": true,
100
+ "detail": "ok"
101
+ }
102
+ ]
holdout.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "problems": 152,
3
+ "official_T0_on_test": 0.8289722147288913,
4
+ "dev_selected_on_test": {
5
+ "1": 0.8448880496358241,
6
+ "2": 0.9482060965740491,
7
+ "3": 0.9638521715673051,
8
+ "5": 0.9660102508767198
9
+ }
10
+ }
invalid_suites.json ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "elu": [
3
+ "T4_branch_threshold_sweep",
4
+ "T5_negative_exponential_ladder",
5
+ "T6_misaligned_alternating_tail"
6
+ ],
7
+ "gelu": [
8
+ "T4_misaligned_fp16_overflow",
9
+ "T5_erf_transition_grid"
10
+ ],
11
+ "leakyrelu": [
12
+ "T4_misaligned_tail_spikes",
13
+ "T5_threshold_transition_grid"
14
+ ],
15
+ "logsoftmax": [
16
+ "T3_spiky",
17
+ "T4_tail_spike_misaligned",
18
+ "T5_first_iteration_mass",
19
+ "T6_alternating_lane_magnitude",
20
+ "T7_fp16_overflow_misaligned"
21
+ ],
22
+ "matmul": [
23
+ "T4_last_tile_spike"
24
+ ],
25
+ "matmul_mk": [
26
+ "T4_last_tile_spike"
27
+ ],
28
+ "matmul_ta": [
29
+ "T4_last_tile_spike",
30
+ "T5_boundary_positional_ramps",
31
+ "T6_single_tail_mass_spike",
32
+ "T7_tile_minus1_alternating"
33
+ ],
34
+ "max": [
35
+ "T4_edge_row_spike",
36
+ "T5_all_negative",
37
+ "T6_alternating_duplicate_maxima",
38
+ "T7_first_middle_last_ties",
39
+ "T8_signed_zero_tie_order"
40
+ ],
41
+ "selu": [
42
+ "T4_branch_threshold_neighborhood",
43
+ "T5_misaligned_negative_stripes",
44
+ "T6_negative_exponential_sweep"
45
+ ],
46
+ "sigmoid": [
47
+ "T4_misaligned_alternating_tail",
48
+ "T5_fp16_transition_grid"
49
+ ],
50
+ "softmax": [
51
+ "T3_spiky",
52
+ "T4_tail_spike_misaligned"
53
+ ]
54
+ }
ladder/BRIEF_R1.md ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Task: write extra test inputs for a GPU kernel benchmark problem
2
+
3
+ The benchmark checks a candidate CUDA kernel against a PyTorch reference with
4
+ torch.allclose(atol=1e-2, rtol=1e-2) on a few input tensors. You suspect the
5
+ current inputs may miss subtle bugs. Write 2 ADDITIONAL test-input suites for
6
+ the assigned problem.
7
+
8
+ Deliverable: ladder/suites_R1_<problem>.py containing exactly:
9
+
10
+ ```python
11
+ import torch
12
+
13
+ def suites():
14
+ def s1(trial):
15
+ g = torch.Generator().manual_seed(1000 + trial)
16
+ # return the SAME list of CPU tensors get_inputs() returns
17
+ # (same count, dtypes, and any shape constraints the kernel requires)
18
+ return [ ... ]
19
+ def s2(trial):
20
+ ...
21
+ return [("R1_a", 2, s1), ("R1_b", 2, s2)]
22
+ ```
23
+
24
+ Read the substrate file you are pointed at to learn the input shapes/dtypes
25
+ (its T0_original suite reproduces the official get_inputs()). Builders must be
26
+ deterministic (seed from trial), return CPU tensors, and respect any shape
27
+ constraints baked into the kernel/launcher. Do not modify any other file.
ladder/BRIEF_R3.md ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Task: kill specific surviving mutants of a GPU kernel (white-box)
2
+
3
+ The assigned problem has known SURVIVING MUTANTS: buggy variants of a correct
4
+ CUDA kernel that the benchmark's current inputs cannot distinguish from the
5
+ correct kernel (checker: torch.allclose(atol=1e-2, rtol=1e-2) vs the PyTorch
6
+ reference). You get the mutant list (rule + mutated source site) in the info
7
+ file you are pointed at. Write 2 test-input suites that make these mutants
8
+ produce detectably different output.
9
+
10
+ How to think: read each mutated site and construct inputs whose correct output
11
+ is sensitive to that exact code path — boundary sizes that exercise remainder
12
+ blocks for guard/bounds mutants, values with distinct magnitudes per position
13
+ for indexing mutants, inputs that stress accumulation for precision mutants,
14
+ non-uniform data for tie-breaking mutants.
15
+
16
+ HARD VALIDITY CONSTRAINT: the CORRECT kernel must still pass. Two correct fp32
17
+ implementations legitimately differ by accumulation order; measured on long
18
+ reductions, SIGNED inputs (randn*s) are safe to about s=100 and falsely flag
19
+ the correct kernel by s=300, while SAME-SIGN inputs stay safe past s=1000.
20
+ Prefer same-sign magnitudes, moderate spikes, structured patterns — not huge
21
+ signed values.
22
+
23
+ Deliverable: ladder/suites_R3_<problem>.py, exactly this contract:
24
+
25
+ ```python
26
+ import torch
27
+
28
+ def suites():
29
+ def s1(trial):
30
+ g = torch.Generator().manual_seed(3000 + trial)
31
+ return [ ... ] # same list of CPU tensors as get_inputs()
32
+ def s2(trial):
33
+ ...
34
+ return [("R3_a", 2, s1), ("R3_b", 2, s2)]
35
+ ```
36
+
37
+ Deterministic builders, CPU tensors, keep every shape constraint the kernel
38
+ requires (read the substrate file's T0_original). Do not modify other files.
ladder_summary.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"total": 1154, "R0": 249, "R1": [495, 1154], "R2": 704, "R3": [626, 1092]}
mechanism_curves.json ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "vacuity": [
3
+ {
4
+ "dim": 64,
5
+ "mean_output": 0.015625,
6
+ "zeros_pass": false,
7
+ "max_undetected_rel_error": 0.3911769908881979
8
+ },
9
+ {
10
+ "dim": 512,
11
+ "mean_output": 0.001953125,
12
+ "zeros_pass": true,
13
+ "max_undetected_rel_error": 3.14493727273657
14
+ },
15
+ {
16
+ "dim": 4096,
17
+ "mean_output": 0.000244140625,
18
+ "zeros_pass": true,
19
+ "max_undetected_rel_error": 25.862332340693683
20
+ },
21
+ {
22
+ "dim": 32768,
23
+ "mean_output": 3.0517578125e-05,
24
+ "zeros_pass": true,
25
+ "max_undetected_rel_error": 208.68726348453492
26
+ },
27
+ {
28
+ "dim": 262144,
29
+ "mean_output": 3.814697265625e-06,
30
+ "zeros_pass": true,
31
+ "max_undetected_rel_error": 1671.7297973627865
32
+ },
33
+ {
34
+ "dim": 393216,
35
+ "mean_output": 2.543131586207892e-06,
36
+ "zeros_pass": true,
37
+ "max_undetected_rel_error": 2508.5181884696794
38
+ }
39
+ ],
40
+ "variance_ceiling": [
41
+ {
42
+ "dist": "signed",
43
+ "scale": 1,
44
+ "max_diff": 0.00091552734375,
45
+ "worst_margin": -0.009912180714309216,
46
+ "false_kill": false
47
+ },
48
+ {
49
+ "dist": "signed",
50
+ "scale": 3,
51
+ "max_diff": 0.002685546875,
52
+ "worst_margin": -0.009806494228541851,
53
+ "false_kill": false
54
+ },
55
+ {
56
+ "dist": "signed",
57
+ "scale": 10,
58
+ "max_diff": 0.00927734375,
59
+ "worst_margin": -0.009194783866405487,
60
+ "false_kill": false
61
+ },
62
+ {
63
+ "dist": "signed",
64
+ "scale": 30,
65
+ "max_diff": 0.0234375,
66
+ "worst_margin": -0.007786626927554607,
67
+ "false_kill": false
68
+ },
69
+ {
70
+ "dist": "signed",
71
+ "scale": 100,
72
+ "max_diff": 0.083984375,
73
+ "worst_margin": -0.0010235980153083801,
74
+ "false_kill": false
75
+ },
76
+ {
77
+ "dist": "signed",
78
+ "scale": 300,
79
+ "max_diff": 0.3125,
80
+ "worst_margin": 0.021475525572896004,
81
+ "false_kill": true
82
+ },
83
+ {
84
+ "dist": "signed",
85
+ "scale": 1000,
86
+ "max_diff": 0.84375,
87
+ "worst_margin": 0.06371429562568665,
88
+ "false_kill": true
89
+ },
90
+ {
91
+ "dist": "signed",
92
+ "scale": 3000,
93
+ "max_diff": 2.5625,
94
+ "worst_margin": 0.28810545802116394,
95
+ "false_kill": true
96
+ },
97
+ {
98
+ "dist": "positive",
99
+ "scale": 1,
100
+ "max_diff": 0.013916015625,
101
+ "worst_margin": -30.65578269958496,
102
+ "false_kill": false
103
+ },
104
+ {
105
+ "dist": "positive",
106
+ "scale": 3,
107
+ "max_diff": 0.048828125,
108
+ "worst_margin": -91.94537353515625,
109
+ "false_kill": false
110
+ },
111
+ {
112
+ "dist": "positive",
113
+ "scale": 10,
114
+ "max_diff": 0.1328125,
115
+ "worst_margin": -306.4940185546875,
116
+ "false_kill": false
117
+ },
118
+ {
119
+ "dist": "positive",
120
+ "scale": 30,
121
+ "max_diff": 0.5,
122
+ "worst_margin": -919.3250122070312,
123
+ "false_kill": false
124
+ },
125
+ {
126
+ "dist": "positive",
127
+ "scale": 100,
128
+ "max_diff": 1.5625,
129
+ "worst_margin": -3064.599609375,
130
+ "false_kill": false
131
+ },
132
+ {
133
+ "dist": "positive",
134
+ "scale": 300,
135
+ "max_diff": 4.0,
136
+ "worst_margin": -9193.2548828125,
137
+ "false_kill": false
138
+ },
139
+ {
140
+ "dist": "positive",
141
+ "scale": 1000,
142
+ "max_diff": 16.0,
143
+ "worst_margin": -30642.939453125,
144
+ "false_kill": false
145
+ },
146
+ {
147
+ "dist": "positive",
148
+ "scale": 3000,
149
+ "max_diff": 47.0,
150
+ "worst_margin": -91944.0078125,
151
+ "false_kill": false
152
+ }
153
+ ]
154
+ }
miss_patterns.json ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "note": "Miss-pattern table behind figs/fig_matrix.pdf (operator scale, witnessed accounting). Each pattern lists which protocols miss the mutant; 'other' collapses the long tail of rarer patterns. Derived from results/audit_*.jsonl, screen_*.jsonl, matrix_*.jsonl, recheck_*.jsonl.",
3
+ "protocols": [
4
+ "Official",
5
+ "KBV x3",
6
+ "KBV x0.01",
7
+ "KBV x-1",
8
+ "CI-style fuzz",
9
+ "Ours"
10
+ ],
11
+ "denominator": 7320,
12
+ "caught_by_all": 6083,
13
+ "contested": 1237,
14
+ "patterns": [
15
+ {
16
+ "missed_by": [
17
+ true,
18
+ true,
19
+ true,
20
+ true,
21
+ true,
22
+ false
23
+ ],
24
+ "count": 643
25
+ },
26
+ {
27
+ "missed_by": [
28
+ true,
29
+ true,
30
+ true,
31
+ true,
32
+ false,
33
+ false
34
+ ],
35
+ "count": 254
36
+ },
37
+ {
38
+ "missed_by": [
39
+ true,
40
+ false,
41
+ true,
42
+ true,
43
+ false,
44
+ false
45
+ ],
46
+ "count": 135
47
+ },
48
+ {
49
+ "missed_by": [
50
+ true,
51
+ false,
52
+ true,
53
+ true,
54
+ true,
55
+ false
56
+ ],
57
+ "count": 51
58
+ },
59
+ {
60
+ "missed_by": [
61
+ true,
62
+ true,
63
+ false,
64
+ true,
65
+ false,
66
+ false
67
+ ],
68
+ "count": 46
69
+ },
70
+ {
71
+ "missed_by": [
72
+ true,
73
+ false,
74
+ false,
75
+ false,
76
+ false,
77
+ false
78
+ ],
79
+ "count": 38
80
+ },
81
+ {
82
+ "missed_by": [
83
+ true,
84
+ true,
85
+ true,
86
+ false,
87
+ false,
88
+ false
89
+ ],
90
+ "count": 13
91
+ },
92
+ {
93
+ "missed_by": [
94
+ true,
95
+ true,
96
+ false,
97
+ true,
98
+ true,
99
+ false
100
+ ],
101
+ "count": 10
102
+ },
103
+ {
104
+ "missed_by": [
105
+ true,
106
+ false,
107
+ true,
108
+ false,
109
+ false,
110
+ false
111
+ ],
112
+ "count": 7
113
+ },
114
+ {
115
+ "missed_by": [
116
+ true,
117
+ false,
118
+ false,
119
+ true,
120
+ true,
121
+ false
122
+ ],
123
+ "count": 6
124
+ },
125
+ {
126
+ "missed_by": [
127
+ true,
128
+ false,
129
+ true,
130
+ false,
131
+ true,
132
+ false
133
+ ],
134
+ "count": 6
135
+ },
136
+ {
137
+ "missed_by": [
138
+ true,
139
+ true,
140
+ true,
141
+ false,
142
+ true,
143
+ false
144
+ ],
145
+ "count": 6
146
+ }
147
+ ],
148
+ "other": 22,
149
+ "total_missed": [
150
+ 1237,
151
+ 985,
152
+ 1124,
153
+ 1155,
154
+ 727,
155
+ 10
156
+ ]
157
+ }
pipeline/adjudicate.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Adjudicate the still-unkilled (no-witness) mutants: equivalent, or
2
+ oracle-blind?
3
+
4
+ Phase 1 — random bombardment: each surviving mutant gets N randomized inputs
5
+ (mixed distributions, scales, AND shapes incl. misaligned) under the standard
6
+ allclose oracle. A kill => witness found; record it (these mutants move into
7
+ the killable pool).
8
+
9
+ Phase 2 — compute-sanitizer: survivors of phase 1 run once on a small input
10
+ under compute-sanitizer. Memory errors reported => real bug, oracle-blind
11
+ (needs a sanitizer channel in the harness). Clean => likely equivalent.
12
+
13
+ Output: results/adjudicate.jsonl + summary. Resume-safe like other runners.
14
+ Usage: python3 adjudicate.py [--worker P]
15
+ """
16
+ import ctypes
17
+ import json
18
+ import os
19
+ import subprocess
20
+ import sys
21
+
22
+ HERE = os.path.dirname(os.path.abspath(__file__))
23
+ sys.path.insert(0, HERE)
24
+ RESULTS = os.path.join(HERE, "results")
25
+
26
+ import kernels_def as K # noqa: E402
27
+ import problems_ext # noqa: E402,F401
28
+ import mutator # noqa: E402
29
+ from nvrtc_tce import compile_ptx, device_source # noqa: E402
30
+ from screen_mutants import NvrtcKernel, compare, kernel_name, ref_fn_for # noqa: E402
31
+ from full_matrix import screening_classes # noqa: E402
32
+
33
+ FUZZ_TRIALS = 60
34
+
35
+
36
+ def surviving_ids(problem):
37
+ """no_witness mutants not killed by the full matrix either."""
38
+ cls = screening_classes(problem)
39
+ nw = {i for i, r in cls.items() if r["cls"] == "no_witness"}
40
+ mpath = os.path.join(RESULTS, f"matrix_{problem}.jsonl")
41
+ if os.path.exists(mpath):
42
+ for line in open(mpath):
43
+ r = json.loads(line)
44
+ if r["type"] == "CELL" and r["outcome"] == "killed":
45
+ nw.discard(r["id"])
46
+ return nw
47
+
48
+
49
+ def rand_inputs(problem, trial, torch):
50
+ """Randomized shapes (aligned AND misaligned) + distributions."""
51
+ g = torch.Generator().manual_seed(7000 + trial)
52
+ torch.manual_seed(7000 + trial)
53
+
54
+ def d(lo, hi):
55
+ return int(torch.randint(lo, hi, (1,), generator=g).item())
56
+
57
+ def vals(*shape):
58
+ fam = d(0, 4)
59
+ scale = float(10.0 ** d(-2, 3))
60
+ base = (torch.rand(*shape) if fam == 0 else
61
+ torch.randn(*shape) if fam == 1 else
62
+ (torch.rand(*shape) - 0.5) * 2 if fam == 2 else
63
+ torch.randn(*shape).abs())
64
+ return base * scale
65
+
66
+ if problem in ("relu", "leakyrelu", "gelu", "sigmoid"):
67
+ return [vals(d(1, 64), d(200, 5000))]
68
+ if problem in ("softmax", "logsoftmax"):
69
+ return [vals(d(1, 48), d(200, 8000))]
70
+ if problem == "matmul":
71
+ n = d(30, 700)
72
+ return [vals(n, n), vals(n, n)]
73
+ if problem in ("matmul_mk", "matmul_ta"):
74
+ m, k, n = d(30, 500), d(30, 700), d(30, 500)
75
+ A = vals(k, m) if problem == "matmul_ta" else vals(m, k)
76
+ return [A, vals(k, n)]
77
+ if problem in ("sum", "mean", "max"):
78
+ return [vals(d(2, 16), d(50, 800), d(50, 800))]
79
+ if problem == "rmsnorm":
80
+ return [vals(d(2, 8), d(3, 32), d(5, 40), d(5, 40))]
81
+ raise ValueError(problem)
82
+
83
+
84
+ def worker(problem):
85
+ import torch
86
+ jpath = os.path.join(RESULTS, "adjudicate.jsonl")
87
+ done = set()
88
+ pending = None
89
+ if os.path.exists(jpath):
90
+ for line in open(jpath):
91
+ r = json.loads(line)
92
+ if r["type"] == "ASTART" and r["problem"] == problem:
93
+ pending = r["id"]
94
+ elif r["type"] == "ADJ" and r["problem"] == problem:
95
+ done.add(r["id"])
96
+ pending = None
97
+ journal = open(jpath, "a")
98
+
99
+ def emit(**rec):
100
+ journal.write(json.dumps(rec) + "\n")
101
+ journal.flush()
102
+ os.fsync(journal.fileno())
103
+
104
+ if pending is not None:
105
+ emit(type="ADJ", problem=problem, id=pending, verdict="oracle_blind",
106
+ detail="crashed during fuzz (crash witness found)")
107
+ done.add(pending)
108
+
109
+ ids = sorted(surviving_ids(problem) - done)
110
+ if not ids:
111
+ return
112
+ mutants = {m["id"]: m for m in
113
+ mutator.generate(problem, device_source(K.PROBLEMS[problem]["cuda"]))}
114
+ ref_fn = ref_fn_for(problem)
115
+ torch.zeros(1, device="cuda")
116
+ cuda_lib = ctypes.CDLL("libcuda.so.1")
117
+
118
+ for mid in ids:
119
+ src = mutants[mid]["src"].replace("__global__ void",
120
+ 'extern "C" __global__ void')
121
+ ptx = compile_ptx(src, "m.cu")
122
+ emit(type="ASTART", problem=problem, id=mid)
123
+ kern = NvrtcKernel(cuda_lib, ptx, kernel_name(problem))
124
+ witness = None
125
+ try:
126
+ for t in range(FUZZ_TRIALS):
127
+ cpu_in = rand_inputs(problem, t, torch)
128
+ gpu_in = [x.cuda() for x in cpu_in]
129
+ with torch.no_grad():
130
+ ref = ref_fn(*gpu_in).cpu()
131
+ out = kern.launch(problem, gpu_in, torch)
132
+ r = compare(ref, out.cpu(), torch)
133
+ del gpu_in, out, ref
134
+ torch.cuda.empty_cache()
135
+ if r != "survived":
136
+ witness = t
137
+ break
138
+ kern.unload()
139
+ except RuntimeError as e:
140
+ emit(type="ADJ", problem=problem, id=mid, verdict="oracle_blind",
141
+ detail=f"cuda crash in fuzz t{t}: {str(e)[:60]}")
142
+ journal.close()
143
+ sys.exit(3)
144
+ if witness is not None:
145
+ emit(type="ADJ", problem=problem, id=mid, verdict="witness_found",
146
+ detail=f"fuzz trial {witness}")
147
+ else:
148
+ emit(type="ADJ", problem=problem, id=mid, verdict="fuzz_survivor")
149
+ journal.close()
150
+
151
+
152
+ def sanitizer_phase():
153
+ """Run each fuzz_survivor once under compute-sanitizer on a small input."""
154
+ jpath = os.path.join(RESULTS, "adjudicate.jsonl")
155
+ surv = []
156
+ for line in open(jpath):
157
+ r = json.loads(line)
158
+ if r["type"] == "ADJ" and r["verdict"] == "fuzz_survivor":
159
+ surv.append((r["problem"], r["id"]))
160
+ results = []
161
+ for problem, mid in surv:
162
+ env = dict(os.environ, PYTORCH_NO_CUDA_MEMORY_CACHING="1")
163
+ p = subprocess.run(
164
+ ["/usr/local/cuda/bin/compute-sanitizer", "--tool", "memcheck",
165
+ sys.executable, os.path.join(HERE, "sanitizer_probe.py"),
166
+ problem, mid],
167
+ capture_output=True, text=True, timeout=300, env=env)
168
+ txt = p.stdout + p.stderr
169
+ clean = "ERROR SUMMARY: 0 errors" in txt
170
+ verdict = "likely_equivalent" if clean else "oracle_blind_memerror"
171
+ results.append(dict(type="SAN", problem=problem, id=mid, verdict=verdict))
172
+ print(f"[sanitizer] {problem}/{mid}: {verdict}", flush=True)
173
+ with open(jpath, "a") as f:
174
+ for r in results:
175
+ f.write(json.dumps(r) + "\n")
176
+
177
+
178
+ def summary():
179
+ import collections
180
+ jpath = os.path.join(RESULTS, "adjudicate.jsonl")
181
+ adj, san = {}, {}
182
+ for line in open(jpath):
183
+ r = json.loads(line)
184
+ if r["type"] == "ADJ":
185
+ adj[(r["problem"], r["id"])] = r["verdict"]
186
+ elif r["type"] == "SAN":
187
+ san[(r["problem"], r["id"])] = r["verdict"]
188
+ c = collections.Counter()
189
+ for k, v in adj.items():
190
+ c[san.get(k, v)] += 1
191
+ print("adjudication:", dict(c), flush=True)
192
+
193
+
194
+ if __name__ == "__main__":
195
+ if len(sys.argv) > 2 and sys.argv[1] == "--worker":
196
+ worker(sys.argv[2])
197
+ else:
198
+ for problem in K.PROBLEMS:
199
+ for attempt in range(40):
200
+ rc = subprocess.run(
201
+ [sys.executable, __file__, "--worker", problem]).returncode
202
+ if rc == 0:
203
+ break
204
+ print(f"[adjudicate] {problem}: fuzz done", flush=True)
205
+ sanitizer_phase()
206
+ summary()
207
+ print("[adjudicate] ALL DONE", flush=True)
pipeline/analyze_cover.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Greedy set-cover over the full kill matrix.
2
+
3
+ Answers: per problem, what is the minimal number of targeted inputs needed to
4
+ kill every killable mutant, and what does the kill-rate-vs-budget curve look
5
+ like vs the original KernelBench inputs.
6
+
7
+ Killable mutant = classified killed_by_T0 / high_value in screening, plus any
8
+ no_witness mutant that the full matrix newly killed. Crash-killed mutants use
9
+ their screening witness as their kill column.
10
+ """
11
+ import json
12
+ import os
13
+ import collections
14
+
15
+ HERE = os.path.dirname(os.path.abspath(__file__))
16
+ RESULTS = os.path.join(HERE, "results")
17
+
18
+ import sys
19
+ sys.path.insert(0, HERE)
20
+ import kernels_def as K # noqa: E402
21
+ import problems_ext # noqa: E402,F401
22
+ from suite_filter import valid_suites # noqa: E402
23
+
24
+
25
+ def probe_witness_to_suite(problem, w):
26
+ """Map a probe crash witness to the closest targeted-suite column."""
27
+ w = w.split(":", 1)[-1]
28
+ names = [n for n, _, _ in valid_suites(problem) if n != "T0_original"]
29
+ if "misaligned" in w or "spike" in w:
30
+ for n in names:
31
+ if "misaligned" in n or "spike" in n:
32
+ return n
33
+ if "large" in w:
34
+ for n in names:
35
+ if "large" in n:
36
+ return n
37
+ return names[0]
38
+
39
+
40
+ def load(problem):
41
+ """Return (kills: suite -> set(mutant), killable: set, t0_killed: set)."""
42
+ cls = {}
43
+ for line in open(os.path.join(RESULTS, f"screen_{problem}.jsonl")):
44
+ r = json.loads(line)
45
+ if r["type"] == "RESULT":
46
+ cls[r["id"]] = r
47
+ kills = collections.defaultdict(set)
48
+ t0_killed = set()
49
+ killable = set()
50
+ for mid, r in cls.items():
51
+ c = r["cls"]
52
+ if c == "killed_by_T0":
53
+ t0_killed.add(mid)
54
+ killable.add(mid)
55
+ if r.get("reason") in ("crash", "probe_crash", "cuda_poisoned"):
56
+ # crashes on T0-like inputs; no targeted data — T0 column only
57
+ kills["__T0__"].add(mid)
58
+ elif c == "high_value":
59
+ killable.add(mid)
60
+ w = r.get("witness")
61
+ if w and w.startswith("probe:"):
62
+ kills[probe_witness_to_suite(problem, w)].add(mid)
63
+ mpath = os.path.join(RESULTS, f"matrix_{problem}.jsonl")
64
+ if os.path.exists(mpath):
65
+ for line in open(mpath):
66
+ r = json.loads(line)
67
+ if r["type"] == "CELL" and r["outcome"] == "killed":
68
+ kills[r["suite"]].add(r["id"])
69
+ killable.add(r["id"]) # no_witness mutants newly killed
70
+ kills["__T0__"] |= t0_killed
71
+ return kills, killable, t0_killed
72
+
73
+
74
+ def greedy_cover(kills, universe):
75
+ chosen, covered = [], set()
76
+ pool = {s: m & universe for s, m in kills.items() if s != "__T0__"}
77
+ while covered != universe:
78
+ best = max(pool, key=lambda s: len(pool[s] - covered), default=None)
79
+ if best is None or not (pool[best] - covered):
80
+ break
81
+ chosen.append((best, len(pool[best] - covered)))
82
+ covered |= pool[best]
83
+ return chosen, covered
84
+
85
+
86
+ def main():
87
+ grand_universe = grand_covered = 0
88
+ rows = []
89
+ newly = 0
90
+ for problem in K.PROBLEMS:
91
+ kills, killable, t0_killed = load(problem)
92
+ targeted_killable = set()
93
+ for s, m in kills.items():
94
+ if s != "__T0__":
95
+ targeted_killable |= m
96
+ # universe for the cover: everything killable by targeted inputs
97
+ chosen, covered = greedy_cover(kills, targeted_killable & killable)
98
+ uncovered_total = killable - covered # only killable via T0/crash
99
+ rows.append((problem, len(killable), len(t0_killed), chosen,
100
+ len(covered), len(uncovered_total)))
101
+ grand_universe += len(killable)
102
+ grand_covered += len(covered)
103
+ print(f"{problem:12s} killable={len(killable):3d} (T0-killed {len(t0_killed):3d}) "
104
+ f"greedy cover: {[(s, k) for s, k in chosen]} "
105
+ f"covered={len(covered)} T0/crash-only={len(uncovered_total)}")
106
+ print()
107
+ print(f"TOTAL killable={grand_universe}, covered by targeted inputs={grand_covered}")
108
+ # budget curve: fraction of all killable mutants killed with k inputs/problem
109
+ print("\nkill-rate vs inputs-per-problem budget:")
110
+ for k in range(1, 6):
111
+ tot = 0
112
+ for problem, killable_n, t0_n, chosen, covered_n, unc in rows:
113
+ tot += sum(c for _, c in chosen[:k])
114
+ print(f" k={k}: {tot}/{grand_universe} = {tot / grand_universe:.1%}")
115
+ print(" (原版 KernelBench 5 组输入对高价值池的杀伤率: 0%)")
116
+
117
+
118
+ if __name__ == "__main__":
119
+ main()
pipeline/analyze_holdout.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Dev/test holdout for the set-cover suites (anti-overfitting check, §7).
2
+
3
+ Within each problem, killable mutants are split 50/50 by a stable hash of the
4
+ mutant id. Suites are selected greedily on the DEV half only; detection is then
5
+ reported on the held-out TEST half. If the optimized-suite numbers were an
6
+ artifact of selecting on the full pool, they collapse here.
7
+ """
8
+ import glob, hashlib, json, os, collections
9
+
10
+ RESULTS = "results"
11
+ # consult the invalid-suite blocklist directly (no registry import needed)
12
+ try:
13
+ _bl = json.load(open(f"{RESULTS}/invalid_suites.json"))
14
+ BLOCK = {(p, s) for p, ss in _bl.items() for s in ss} if isinstance(_bl, dict) \
15
+ else {(r["problem"], r["suite"]) for r in _bl}
16
+ except Exception:
17
+ BLOCK = set()
18
+
19
+
20
+ def load_problem(p):
21
+ t0, cover = set(), collections.defaultdict(set)
22
+ sf = f"{RESULTS}/screen_{p}.jsonl"
23
+ if not os.path.exists(sf):
24
+ return None
25
+ for line in open(sf):
26
+ r = json.loads(line)
27
+ if r["type"] == "RESULT" and r["cls"] == "killed_by_T0":
28
+ t0.add(r["id"])
29
+ ok = lambda s: (p, s) not in BLOCK
30
+ for jf, key in ((f"{RESULTS}/matrix_{p}.jsonl", "CELL"),
31
+ (f"{RESULTS}/recheck_{p}.jsonl", "RCELL")):
32
+ if not os.path.exists(jf):
33
+ continue
34
+ for line in open(jf):
35
+ r = json.loads(line)
36
+ if r["type"] == key and r["outcome"] == "killed" and ok(r["suite"]):
37
+ cover[r["suite"]].add(r["id"])
38
+ return t0, cover
39
+
40
+
41
+ def greedy(cover, universe, budget):
42
+ chosen, covered = [], set()
43
+ for _ in range(budget):
44
+ best = max(cover, key=lambda s: len((cover[s] & universe) - covered),
45
+ default=None)
46
+ if best is None or not (cover[best] & universe) - covered:
47
+ break
48
+ chosen.append(best)
49
+ covered |= cover[best] & universe
50
+ return chosen
51
+
52
+
53
+ def main():
54
+ budgets = [1, 2, 3, 5]
55
+ agg = {b: [0, 0] for b in budgets} # killed, total on TEST
56
+ t0_agg = [0, 0]
57
+ n_prob = 0
58
+ for f in sorted(glob.glob(f"{RESULTS}/screen_*.jsonl")):
59
+ p = os.path.basename(f)[7:-6]
60
+ if p.startswith("L3"):
61
+ continue
62
+ loaded = load_problem(p)
63
+ if not loaded:
64
+ continue
65
+ t0, cover = loaded
66
+ cover = dict(cover)
67
+ cover["T0_original"] = set(t0) # T0 selectable like any suite
68
+ killable = set().union(t0, *cover.values()) if cover else set(t0)
69
+ if len(killable) < 4:
70
+ continue
71
+ n_prob += 1
72
+ dev = {m for m in killable
73
+ if int(hashlib.md5(m.encode()).hexdigest(), 16) % 2 == 0}
74
+ test = killable - dev
75
+ if not test:
76
+ continue
77
+ t0_agg[0] += len(t0 & test); t0_agg[1] += len(test)
78
+ for b in budgets:
79
+ chosen = greedy(cover, dev, b)
80
+ killed = set().union(*(cover[s] for s in chosen)) if chosen else set()
81
+ agg[b][0] += len(killed & test); agg[b][1] += len(test)
82
+ out = dict(problems=n_prob,
83
+ official_T0_on_test=t0_agg[0] / t0_agg[1],
84
+ dev_selected_on_test={b: agg[b][0] / agg[b][1] for b in budgets})
85
+ json.dump(out, open(f"{RESULTS}/holdout.json", "w"), indent=1)
86
+ print(f"problems={n_prob} test-half detection:")
87
+ print(f" official 5 random inputs : {out['official_T0_on_test']:.1%}")
88
+ for b in budgets:
89
+ print(f" dev-selected, budget {b} : {out['dev_selected_on_test'][b]:.1%}")
90
+
91
+ if __name__ == "__main__":
92
+ main()
pipeline/audit_matrix.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Audit competitor test recipes on our validated mutant pool.
2
+
3
+ For every problem: evaluate the CORRECT kernel plus every killable mutant
4
+ against the competitor suite columns (KBV_* four distributions from
5
+ KernelBench-Verified; CI_fuzz seeded fuzzing from The Correctness Illusion).
6
+
7
+ Reports, per column family:
8
+ - mutation score = killable mutants killed / all killable
9
+ - false-kill rate = does the column reject the CORRECT kernel? (per problem)
10
+
11
+ Journal: results/audit_<problem>.jsonl (same START/CELL resume protocol).
12
+ Usage: python3 audit_matrix.py # orchestrator
13
+ python3 audit_matrix.py --worker P
14
+ """
15
+ import ctypes
16
+ import json
17
+ import os
18
+ import subprocess
19
+ import sys
20
+
21
+ HERE = os.path.dirname(os.path.abspath(__file__))
22
+ sys.path.insert(0, HERE)
23
+ RESULTS = os.path.join(HERE, "results")
24
+
25
+ import kernels_def as K # noqa: E402
26
+ import problems_ext # noqa: E402,F401
27
+ import mutator # noqa: E402
28
+ import competitor_suites as C # noqa: E402
29
+ from nvrtc_tce import externc, compile_ptx, device_source # noqa: E402
30
+ from screen_mutants import install_watchdog, pet_watchdog, NvrtcKernel, compare, kernel_name, ref_fn_for # noqa: E402
31
+ from full_matrix import screening_classes # noqa: E402
32
+
33
+
34
+ SHARD_ID = int(os.environ.get("SHARD_ID", "0"))
35
+ SHARD_N = int(os.environ.get("SHARD_N", "1"))
36
+
37
+
38
+ AUDIT_STEAL = os.environ.get("STEAL", "0") == "1"
39
+
40
+
41
+ def my_problems():
42
+ """Hash slice, or (STEAL=1) any problem with no audit journal yet — used
43
+ when a worker disappears and its slice would otherwise go unaudited."""
44
+ import hashlib
45
+ if AUDIT_STEAL:
46
+ out = []
47
+ for p in K.PROBLEMS:
48
+ jp = os.path.join(RESULTS, f"audit_{p}.jsonl")
49
+ if os.path.exists(jp) and "ADONE" in open(jp).read():
50
+ continue
51
+ claim = os.path.join(RESULTS, f".aclaim_{p}")
52
+ try:
53
+ os.close(os.open(claim, os.O_CREAT | os.O_EXCL | os.O_WRONLY))
54
+ out.append(p)
55
+ except FileExistsError:
56
+ continue
57
+ return out
58
+ return [p for p in K.PROBLEMS
59
+ if int(hashlib.md5(p.encode()).hexdigest()[:8], 16) % SHARD_N == SHARD_ID]
60
+
61
+
62
+ def killable_ids(problem):
63
+ cls = screening_classes(problem)
64
+ ids = {i for i, r in cls.items()
65
+ if r["cls"] in ("killed_by_T0", "high_value")
66
+ and r.get("reason") not in ("crash", "probe_crash", "cuda_poisoned")}
67
+ mpath = os.path.join(RESULTS, f"matrix_{problem}.jsonl")
68
+ if os.path.exists(mpath):
69
+ for line in open(mpath):
70
+ r = json.loads(line)
71
+ if r["type"] == "CELL" and r["outcome"] == "killed":
72
+ ids.add(r["id"])
73
+ return ids
74
+
75
+
76
+ def worker(problem):
77
+ install_watchdog()
78
+ import torch
79
+ jpath = os.path.join(RESULTS, f"audit_{problem}.jsonl")
80
+ done, pending = set(), None
81
+ if os.path.exists(jpath):
82
+ for line in open(jpath):
83
+ r = json.loads(line)
84
+ if r["type"] == "START":
85
+ pending = (r["id"], r["suite"], r.get("trial", 0))
86
+ elif r["type"] == "CELL":
87
+ done.add((r["id"], r["suite"], r.get("trial", 0)))
88
+ pending = None
89
+ journal = open(jpath, "a")
90
+
91
+ def emit(**rec):
92
+ journal.write(json.dumps(rec) + "\n")
93
+ journal.flush()
94
+ os.fsync(journal.fileno())
95
+
96
+ if pending is not None:
97
+ emit(type="CELL", id=pending[0], suite=pending[1], trial=pending[2],
98
+ outcome="killed", reason="crash")
99
+ done.add(pending)
100
+
101
+ ids = killable_ids(problem)
102
+ _ms = list(mutator.generate(problem, device_source(K.PROBLEMS[problem]["cuda"])))
103
+ _cap = int(os.environ.get("MUTANT_CAP", "0"))
104
+ if _cap:
105
+ _ms = mutator.stratified_sample(_ms, _cap) # same sample as screening
106
+ mutants = {m["id"]: m for m in _ms}
107
+ variants = [("correct", device_source(K.PROBLEMS[problem]["cuda"]))]
108
+ variants += [(mid, mutants[mid]["src"]) for mid in sorted(ids) if mid in mutants]
109
+
110
+ columns = C.competitor_columns(problem)
111
+ ref_fn = ref_fn_for(problem)
112
+ torch.zeros(1, device="cuda")
113
+ cuda_lib = ctypes.CDLL("libcuda.so.1")
114
+
115
+ cache = {}
116
+
117
+ # Columns are derived ON THE GPU from a single uploaded base: KBV's D2/D3/D4
118
+ # are scalar multiples, and CI's fuzz values can be drawn directly on device.
119
+ # Building each column as a fresh multi-GB CPU tensor dominated the runtime.
120
+ gpu_base = {}
121
+
122
+ def _base_gpu():
123
+ if not gpu_base:
124
+ import competitor_suites as _C
125
+ gpu_base["t"] = [t.cuda() for t in _C._base_inputs(problem)]
126
+ return gpu_base["t"]
127
+
128
+ KBV_FACTOR = {"KBV_D2_large": 3.0, "KBV_D3_small": 0.01,
129
+ "KBV_D4_negated": -1.0}
130
+
131
+ def get_pair(sname, builder, trial):
132
+ key = (sname, trial)
133
+ if key not in cache:
134
+ cache.clear()
135
+ torch.cuda.empty_cache()
136
+ base = _base_gpu()
137
+ if sname in KBV_FACTOR:
138
+ f = KBV_FACTOR[sname]
139
+ gpu_in = [t * f if t.dtype.is_floating_point else t
140
+ for t in base]
141
+ elif sname == "CI_fuzz":
142
+ g = torch.Generator(device="cuda").manual_seed(90000 + trial)
143
+ fam = int(torch.randint(0, 4, (1,), generator=g,
144
+ device="cuda").item())
145
+ scale = float(10.0 ** int(torch.randint(-3, 4, (1,), generator=g,
146
+ device="cuda").item()))
147
+ gpu_in = []
148
+ for t in base:
149
+ if not t.dtype.is_floating_point:
150
+ gpu_in.append(t)
151
+ continue
152
+ if fam == 0:
153
+ v = torch.rand(t.shape, generator=g, device="cuda") * scale
154
+ elif fam == 1:
155
+ v = torch.randn(t.shape, generator=g, device="cuda") * scale
156
+ elif fam == 2:
157
+ v = (torch.rand(t.shape, generator=g, device="cuda")
158
+ - 0.5) * 2 * scale
159
+ else:
160
+ v = torch.randn(t.shape, generator=g,
161
+ device="cuda").abs() * scale
162
+ gpu_in.append(v)
163
+ else:
164
+ gpu_in = [t.cuda() for t in builder(trial)]
165
+ with torch.no_grad():
166
+ cache[key] = (gpu_in, ref_fn(*gpu_in)) # ref stays on GPU
167
+ return cache[key]
168
+
169
+ ptx_cache = {}
170
+ # column-major so at most one input set lives on the GPU
171
+ for sname, n_trials, builder in columns:
172
+ for trial in range(n_trials):
173
+ for vid, src in variants:
174
+ if (vid, sname, trial) in done:
175
+ continue
176
+ if vid not in ptx_cache:
177
+ s = externc(src)
178
+ ptx_cache[vid] = compile_ptx(s, "m.cu")
179
+ emit(type="START", id=vid, suite=sname, trial=trial)
180
+ kern = NvrtcKernel(cuda_lib, ptx_cache[vid], kernel_name(problem))
181
+ try:
182
+ gpu_in, ref = get_pair(sname, builder, trial)
183
+ pet_watchdog()
184
+ out = kern.launch(problem, gpu_in, torch)
185
+ # Compare ON THE GPU: pulling each multi-GB output back
186
+ # over PCIe dominated runtime (~2s x mutants x columns).
187
+ r = compare(ref, out, torch)
188
+ # KBV's own oracle is atol=rtol=1e-3; record it too so we
189
+ # can separate the contribution of their INPUTS from the
190
+ # contribution of their tighter TOLERANCE.
191
+ strict = ("survived" if out.shape == ref.shape
192
+ and torch.allclose(ref, out, atol=1e-3, rtol=1e-3)
193
+ else "value_mismatch")
194
+ del out
195
+ torch.cuda.empty_cache()
196
+ kern.unload()
197
+ except RuntimeError as e:
198
+ emit(type="CELL", id=vid, suite=sname, trial=trial,
199
+ outcome="killed", reason="crash", detail=str(e)[:80])
200
+ journal.close()
201
+ sys.exit(3)
202
+ emit(type="CELL", id=vid, suite=sname, trial=trial,
203
+ outcome="survived" if r == "survived" else "killed",
204
+ strict="survived" if strict == "survived" else "killed")
205
+ emit(type="ADONE", problem=problem)
206
+
207
+
208
+ def aggregate():
209
+ import collections
210
+ fam_of = lambda s: "KBV(4-dist)" if s.startswith("KBV") else "CI_fuzz"
211
+ kills = collections.defaultdict(set) # family -> set (problem, mutant)
212
+ false_kill = collections.defaultdict(set) # family -> set problem
213
+ universe = set()
214
+
215
+ # crash-classified mutants: scored analytically (competitor recipes never
216
+ # vary shape, so shape-triggered crashers are unreachable for them; value/
217
+ # any-input crashers are reachable by every family).
218
+ for problem in K.PROBLEMS:
219
+ cls = screening_classes(problem)
220
+ for mid, r in cls.items():
221
+ if r.get("reason") not in ("crash", "probe_crash", "cuda_poisoned"):
222
+ continue
223
+ universe.add((problem, mid))
224
+ w = str(r.get("witness") or "")
225
+ crash_on_aligned = r["cls"] == "killed_by_T0"
226
+ shape_triggered = ("misaligned" in w) or ("spike" in w and "misaligned" in w)
227
+ if crash_on_aligned:
228
+ kills["KBV(4-dist)"].add((problem, mid))
229
+ kills["CI_fuzz"].add((problem, mid))
230
+ elif not shape_triggered: # value-triggered (e.g. large-value probe)
231
+ kills["KBV(4-dist)"].add((problem, mid))
232
+ kills["CI_fuzz"].add((problem, mid))
233
+ # shape-triggered crashers: no credit — their inputs are unreachable
234
+
235
+ for problem in K.PROBLEMS:
236
+ jpath = os.path.join(RESULTS, f"audit_{problem}.jsonl")
237
+ if not os.path.exists(jpath):
238
+ continue
239
+ for mid in killable_ids(problem):
240
+ universe.add((problem, mid))
241
+ for line in open(jpath):
242
+ r = json.loads(line)
243
+ if r["type"] != "CELL" or r["outcome"] != "killed":
244
+ continue
245
+ fam = fam_of(r["suite"])
246
+ if r["id"] == "correct":
247
+ false_kill[fam].add((problem, r["suite"]))
248
+ else:
249
+ kills[fam].add((problem, r["id"]))
250
+ # KBV's D1 column is byte-identical to the benchmark's own T0 input, so
251
+ # every mutant screening recorded as killed_by_T0 is also killed by KBV.
252
+ for problem in K.PROBLEMS: # D1 credit
253
+ for mid, r in screening_classes(problem).items():
254
+ if r["cls"] == "killed_by_T0" and (problem, mid) in universe:
255
+ kills["KBV(4-dist)"].add((problem, mid))
256
+ print(f"universe (killable mutants incl. crash-class): {len(universe)}")
257
+ for fam in ("KBV(4-dist)", "CI_fuzz"):
258
+ k = len(kills[fam] & universe)
259
+ print(f"{fam:12s} mutation score {k}/{len(universe)} = {k/len(universe):.1%} "
260
+ f"false-kills-correct: {sorted(false_kill[fam]) or 'none'}")
261
+ print("(ours, 2 inputs/problem: 98.2%; original KernelBench 5 inputs: 81.2%)")
262
+
263
+
264
+ def worker_batch(problems):
265
+ """Process several problems in ONE process: importing the 188-substrate
266
+ registry costs ~85s, and paying that per problem dominated the runtime.
267
+ Crash isolation is preserved by the orchestrator, which restarts the batch
268
+ and skips whatever the journals show as finished."""
269
+ install_watchdog()
270
+ for p in problems:
271
+ try:
272
+ worker(p)
273
+ except SystemExit:
274
+ raise
275
+ except Exception as e:
276
+ print(f"[audit] {p}: error {str(e)[:80]}", flush=True)
277
+ print(f"[audit] {p}: done", flush=True)
278
+
279
+
280
+ def orchestrate():
281
+ """Registry stays in THIS process; each problem runs in a forked child, so
282
+ a poisoned CUDA context costs one fork (microseconds) instead of an 85s
283
+ registry re-import."""
284
+ from forkpool import isolated_loop
285
+ isolated_loop(my_problems(), worker, label="audit", timeout=2400)
286
+ aggregate()
287
+ print("[audit] ALL DONE", flush=True)
288
+
289
+
290
+ def _orchestrate_old():
291
+ for problem in my_problems():
292
+ for attempt in range(60):
293
+ try:
294
+ rc = subprocess.run([sys.executable, __file__, "--worker", problem],
295
+ timeout=2700).returncode
296
+ except subprocess.TimeoutExpired:
297
+ print(f"[{'matrix' if 'full' in __file__ else 'audit'}] {problem}: TIMEOUT, skipping", flush=True)
298
+ rc = 0
299
+ if rc == 0:
300
+ break
301
+ print(f"[audit] {problem}: done", flush=True)
302
+ aggregate()
303
+ print("[audit] ALL DONE", flush=True)
304
+
305
+
306
+ if __name__ == "__main__":
307
+ if len(sys.argv) > 2 and sys.argv[1] == "--batch":
308
+ worker_batch(sys.argv[2:])
309
+ elif len(sys.argv) > 2 and sys.argv[1] == "--worker":
310
+ worker(sys.argv[2])
311
+ elif len(sys.argv) > 1 and sys.argv[1] == "--aggregate":
312
+ aggregate()
313
+ else:
314
+ orchestrate()
pipeline/candidates_loader.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Load substrate candidate files into the registry.
2
+
3
+ Pending candidates live in substrates/candidate_*.py; gate-approved ones are
4
+ moved to substrates/accepted/. Accepted substrates are loaded automatically by
5
+ problems_ext; pending ones only when explicitly requested (validation gate).
6
+ """
7
+ import ctypes
8
+ import glob
9
+ import importlib.util
10
+ import os
11
+
12
+ import torch
13
+
14
+ import kernels_def as K
15
+
16
+ HERE = os.path.dirname(os.path.abspath(__file__))
17
+
18
+
19
+ def _load_file(path):
20
+ name = os.path.splitext(os.path.basename(path))[0]
21
+ spec = importlib.util.spec_from_file_location(f"substrate_{name}", path)
22
+ mod = importlib.util.module_from_spec(spec)
23
+ spec.loader.exec_module(mod)
24
+ before = set(K.PROBLEMS)
25
+ mod.register(K, torch, ctypes)
26
+ return sorted(set(K.PROBLEMS) - before)
27
+
28
+
29
+ def load_accepted():
30
+ """One broken candidate must not silently drop every other one: load each
31
+ file independently, report failures loudly, keep going."""
32
+ added = []
33
+ for path in sorted(glob.glob(os.path.join(HERE, "substrates", "accepted",
34
+ "candidate_*.py"))):
35
+ try:
36
+ added += _load_file(path)
37
+ except Exception as e:
38
+ import sys
39
+ print(f"[candidates] FAILED to load {os.path.basename(path)}: "
40
+ f"{type(e).__name__}: {e}", file=sys.stderr, flush=True)
41
+ return added
42
+
43
+
44
+ def load_pending():
45
+ added = []
46
+ for path in sorted(glob.glob(os.path.join(HERE, "substrates",
47
+ "candidate_*.py"))):
48
+ added += _load_file(path)
49
+ return added
pipeline/competitor_suites.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Competitor test-suite replications, audited on our mutant pool.
2
+
3
+ A) KernelBench-Verified (arXiv:2607.16241, facebookresearch/kernel_bench_verified)
4
+ Verified against their released source (scripts/generate_hidden_inputs.py):
5
+ four DETERMINISTIC scalings of the problem's own get_inputs() tensors —
6
+
7
+ D1 x * 1.0 original (as-is)
8
+ D2 x * 3.0 large magnitude (overflow / precision hacks)
9
+ D3 x * 0.01 near-zero (underflow / skip-small hacks)
10
+ D4 x * -1.0 negated (ReLU / positivity-assumption hacks)
11
+
12
+ Shapes are never varied; integer/bool tensors are never scaled; configs
13
+ whose reference output is NaN/Inf are dropped at generation time.
14
+ Their oracle uses atol=rtol=1e-3 for fp32 (src/eval.py), stricter than
15
+ KernelBench's 1e-2 — we audit under BOTH so the comparison separates the
16
+ input recipe from the tolerance change.
17
+
18
+ B) The Correctness Illusion (arXiv:2606.20128) — op-schema-aware seeded
19
+ fuzzing over values (no released code; parameters follow the paper text).
20
+
21
+ NOTE: an earlier version of this file guessed `randn * 1e4` for D2. That was
22
+ our error, not theirs — it exceeded the legitimate-variance ceiling and
23
+ false-killed correct kernels. Their actual x3.0 cannot do that.
24
+ """
25
+ import torch as _torch
26
+
27
+ # D1 (x1.0) is byte-identical to the benchmark's own T0 input, whose verdict
28
+ # screening already recorded; re-running it would only burn CPU regenerating
29
+ # the same tensors. It is credited analytically at aggregation time.
30
+ KBV_SCALINGS = [("D2_large", 3.0), ("D3_small", 0.01), ("D4_negated", -1.0)]
31
+
32
+
33
+ def _t0_builder(problem):
34
+ import kernels_def as K
35
+ for n, _, b in K.PROBLEMS[problem]["suites"]():
36
+ if n == "T0_original":
37
+ return b
38
+ return K.PROBLEMS[problem]["suites"]()[0][2]
39
+
40
+
41
+ _BASE_CACHE = {}
42
+
43
+
44
+ def _base_inputs(problem):
45
+ """Generate the problem's T0 tensors once and reuse across all columns."""
46
+ if problem not in _BASE_CACHE:
47
+ _BASE_CACHE.clear() # one problem in memory at a time
48
+ _torch.manual_seed(1000)
49
+ _BASE_CACHE[problem] = _t0_builder(problem)(0)
50
+ return _BASE_CACHE[problem]
51
+
52
+
53
+ def kbv_suites(problem):
54
+ """Their exact protocol: scale the problem's own inputs by a constant."""
55
+
56
+ def make(factor):
57
+ def build(trial):
58
+ return [t * factor if t.dtype.is_floating_point else t
59
+ for t in _base_inputs(problem)]
60
+ return build
61
+
62
+ return [(f"KBV_{name}", 1, make(f)) for name, f in KBV_SCALINGS]
63
+
64
+
65
+ def ci_fuzz_suites(problem, n_trials=3):
66
+ """Seeded value-fuzzing at the original shapes (paper description)."""
67
+
68
+ def build(trial):
69
+ _torch.manual_seed(90000 + trial)
70
+ fam = int(_torch.randint(0, 4, (1,)).item())
71
+ scale = float(10.0 ** int(_torch.randint(-3, 4, (1,)).item()))
72
+ out = []
73
+ for t in _base_inputs(problem):
74
+ if not t.dtype.is_floating_point:
75
+ out.append(t)
76
+ continue
77
+ s = t.shape
78
+ if fam == 0:
79
+ v = _torch.rand(*s) * scale
80
+ elif fam == 1:
81
+ v = _torch.randn(*s) * scale
82
+ elif fam == 2:
83
+ v = (_torch.rand(*s) - 0.5) * 2 * scale
84
+ else:
85
+ v = _torch.randn(*s).abs() * scale
86
+ out.append(v)
87
+ return out
88
+
89
+ return [("CI_fuzz", n_trials, build)]
90
+
91
+
92
+ def competitor_columns(problem):
93
+ return kbv_suites(problem) + ci_fuzz_suites(problem)
pipeline/coverage_report.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Per-task survivor coverage: does every task carry enough mutants that the
2
+ benchmark's ORIGINAL inputs fail to kill?
3
+
4
+ A task with no survivors contributes nothing when scoring a test-input
5
+ generator (nothing left to discriminate on), so the artifact targets a floor
6
+ of MIN_SURVIVORS per task. Tasks below the floor are reported with their
7
+ kernel structure so new subtle-fault rules can be aimed at them.
8
+
9
+ Usage: python3 coverage_report.py [min_survivors]
10
+ """
11
+ import collections
12
+ import glob
13
+ import json
14
+ import os
15
+ import sys
16
+
17
+ HERE = os.path.dirname(os.path.abspath(__file__))
18
+ sys.path.insert(0, HERE)
19
+ RESULTS = os.path.join(HERE, "results")
20
+
21
+ MIN_SURVIVORS = int(sys.argv[1]) if len(sys.argv) > 1 else 3
22
+
23
+
24
+ def structure_hint(problem):
25
+ """Coarse structural class, to guide which rule families could apply."""
26
+ try:
27
+ import kernels_def as K
28
+ import problems_ext # noqa: F401
29
+ import candidates_loader
30
+ candidates_loader.load_accepted()
31
+ from nvrtc_tce import device_source
32
+ src = device_source(K.PROBLEMS[problem]["cuda"])
33
+ except Exception:
34
+ return "?"
35
+ tags = []
36
+ if "__shared__" in src:
37
+ tags.append("shared-mem")
38
+ if "__syncthreads" in src:
39
+ tags.append("barrier")
40
+ if src.count("for (") >= 2:
41
+ tags.append("nested-loop")
42
+ elif "for (" in src:
43
+ tags.append("loop")
44
+ else:
45
+ tags.append("elementwise")
46
+ if "CUDART_INF" in src:
47
+ tags.append("sentinel-reduce")
48
+ if "long long" in src and "out[" in src:
49
+ tags.append("index-out")
50
+ return ",".join(tags)
51
+
52
+
53
+ def main():
54
+ rows = []
55
+ for f in sorted(glob.glob(os.path.join(RESULTS, "screen_*.jsonl"))):
56
+ p = os.path.basename(f)[7:-6]
57
+ c = collections.Counter()
58
+ for line in open(f):
59
+ r = json.loads(line)
60
+ if r["type"] == "RESULT":
61
+ c[r["cls"]] += 1
62
+ total = c["high_value"] + c["killed_by_T0"] + c["no_witness"]
63
+ if not total:
64
+ continue
65
+ surv = c["high_value"] + c["no_witness"]
66
+ rows.append((surv, c["high_value"], total, p))
67
+
68
+ rows.sort()
69
+ thin = [r for r in rows if r[0] < MIN_SURVIVORS]
70
+ print(f"tasks screened: {len(rows)} floor: {MIN_SURVIVORS} survivors/task")
71
+ print(f"below floor: {len(thin)}")
72
+ if thin:
73
+ print(f"\n{'task':30s} {'surv':>4s} {'hv':>3s} {'total':>5s} structure")
74
+ for surv, hv, total, p in thin:
75
+ print(f"{p:30s} {surv:4d} {hv:3d} {total:5d} {structure_hint(p)}")
76
+ agg_s = sum(r[0] for r in rows)
77
+ agg_t = sum(r[2] for r in rows)
78
+ print(f"\npool: {agg_t} mutants, {agg_s} survive original inputs "
79
+ f"({agg_s/agg_t:.1%})")
80
+ print(f"median survivors/task: "
81
+ f"{sorted(r[0] for r in rows)[len(rows)//2]}")
82
+
83
+
84
+ if __name__ == "__main__":
85
+ main()
pipeline/driver.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Orchestrates the mutation experiment on the GPU worker.
2
+
3
+ 1. Pre-compiles all kernel variants in parallel (nvcc, cached by torch ext dir).
4
+ 2. Runs eval_kernel.py per problem in a subprocess, respawning on crash
5
+ (crashing mutants are recorded as killed and skipped on resume).
6
+ 3. Aggregates journals into results/summary.json and results/summary.md.
7
+ """
8
+ import concurrent.futures as cf
9
+ import json
10
+ import os
11
+ import subprocess
12
+ import sys
13
+ import time
14
+
15
+ HERE = os.path.dirname(os.path.abspath(__file__))
16
+ RESULTS = os.path.join(HERE, "results")
17
+ os.makedirs(RESULTS, exist_ok=True)
18
+
19
+ sys.path.insert(0, HERE)
20
+ import kernels_def as K # noqa: E402
21
+
22
+
23
+ def precompile():
24
+ def build(job):
25
+ problem, variant_id, src = job
26
+ t0 = time.time()
27
+ try:
28
+ import eval_kernel
29
+ eval_kernel.build_ext(problem, variant_id, src)
30
+ return (problem, variant_id, "ok", time.time() - t0)
31
+ except Exception as e:
32
+ return (problem, variant_id, f"compile_error: {str(e)[:200]}", time.time() - t0)
33
+
34
+ jobs = [(prob, vid, src) for prob in K.PROBLEMS for vid, src in K.all_variants(prob)]
35
+ print(f"[driver] compiling {len(jobs)} variants ...", flush=True)
36
+ with cf.ThreadPoolExecutor(max_workers=5) as ex:
37
+ for prob, vid, status, dt in ex.map(build, jobs):
38
+ print(f"[compile] {prob}/{vid}: {status} ({dt:.0f}s)", flush=True)
39
+
40
+
41
+ def run_problem(problem):
42
+ journal = os.path.join(RESULTS, f"{problem}.jsonl")
43
+ for attempt in range(40):
44
+ proc = subprocess.run(
45
+ [sys.executable, os.path.join(HERE, "eval_kernel.py"), problem, journal],
46
+ timeout=7200)
47
+ if proc.returncode == 0:
48
+ print(f"[driver] {problem}: done", flush=True)
49
+ return
50
+ print(f"[driver] {problem}: process exited rc={proc.returncode}, respawning "
51
+ f"(attempt {attempt + 1})", flush=True)
52
+ print(f"[driver] {problem}: too many respawns, giving up", flush=True)
53
+
54
+
55
+ def aggregate():
56
+ summary = {}
57
+ for problem in K.PROBLEMS:
58
+ journal = os.path.join(RESULTS, f"{problem}.jsonl")
59
+ if not os.path.exists(journal):
60
+ continue
61
+ res = {}
62
+ for line in open(journal):
63
+ rec = json.loads(line)
64
+ if rec["type"] == "RESULT":
65
+ res[(rec["variant"], rec["suite"])] = rec
66
+ summary[problem] = {f"{v}|{s}": r for (v, s), r in res.items()}
67
+ with open(os.path.join(RESULTS, "summary.json"), "w") as f:
68
+ json.dump(summary, f, indent=1)
69
+
70
+ lines = ["# Mutation experiment results", ""]
71
+ for problem in K.PROBLEMS:
72
+ if problem not in summary:
73
+ continue
74
+ p = K.PROBLEMS[problem]
75
+ suites = [s for s, _, _ in p["suites"]()]
76
+ res = summary[problem]
77
+ lines.append(f"## {problem} ({os.path.basename(p['kb_file'])})")
78
+ lines.append("")
79
+ lines.append("| mutant | category | description | " + " | ".join(suites) + " |")
80
+ lines.append("|---" * (3 + len(suites)) + "|")
81
+ t0_survivors = []
82
+ for vid_info in [dict(id="correct", category="-", desc="correct implementation")] + p["mutants"]:
83
+ vid = vid_info["id"]
84
+ cells = []
85
+ for s in suites:
86
+ r = res.get(f"{vid}|{s}")
87
+ if r is None:
88
+ cells.append("?")
89
+ elif r["status"] == "survived":
90
+ cells.append("SURVIVED")
91
+ elif r["status"] == "skipped_after_crash":
92
+ cells.append("(skipped)")
93
+ else:
94
+ cells.append(f"killed:{r.get('reason', '?')}")
95
+ if vid != "correct" and res.get(f"{vid}|T0_original", {}).get("status") == "survived":
96
+ t0_survivors.append(vid)
97
+ lines.append(f"| {vid} | {vid_info['category']} | {vid_info['desc']} | " + " | ".join(cells) + " |")
98
+ n_mut = len(p["mutants"])
99
+ lines.append("")
100
+ lines.append(f"**T0 (original KernelBench inputs, 5 trials) survivors: "
101
+ f"{len(t0_survivors)}/{n_mut}: {', '.join(t0_survivors) or 'none'}**")
102
+ lines.append("")
103
+ with open(os.path.join(RESULTS, "summary.md"), "w") as f:
104
+ f.write("\n".join(lines))
105
+ print("[driver] summary written", flush=True)
106
+
107
+
108
+ if __name__ == "__main__":
109
+ precompile()
110
+ for problem in K.PROBLEMS:
111
+ run_problem(problem)
112
+ aggregate()
113
+ print("[driver] ALL DONE", flush=True)
pipeline/eval_kernel.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Evaluate all variants (correct + mutants) of one problem against all test suites.
2
+
3
+ Kill criterion follows KernelBench eval: runtime error, shape mismatch, or
4
+ !torch.allclose(ref, out, atol=1e-2, rtol=1e-2) => killed.
5
+
6
+ Writes JSONL journal (one line per variant x suite). Resumable: already-journaled
7
+ (variant, suite) pairs are skipped; a START line without a matching RESULT line
8
+ (previous process died there) is recorded as killed:process_crash, and all
9
+ remaining suites of that variant are skipped.
10
+
11
+ Usage: python3 eval_kernel.py <problem> <journal_path>
12
+ """
13
+ import importlib.util
14
+ import json
15
+ import os
16
+ import sys
17
+
18
+ import torch
19
+
20
+ import kernels_def as K
21
+
22
+ ATOL = RTOL = 1e-2
23
+
24
+
25
+ def load_ref_model(problem):
26
+ p = K.PROBLEMS[problem]
27
+ spec = importlib.util.spec_from_file_location(f"kb_{problem}", p["kb_file"])
28
+ mod = importlib.util.module_from_spec(spec)
29
+ spec.loader.exec_module(mod)
30
+ init = mod.get_init_inputs()
31
+ return mod.Model(*init), init
32
+
33
+
34
+ def build_ext(problem, variant_id, cuda_src):
35
+ from torch.utils.cpp_extension import load_inline
36
+ p = K.PROBLEMS[problem]
37
+ return load_inline(
38
+ name=f"{problem}_{variant_id}",
39
+ cpp_sources=p["cpp"],
40
+ cuda_sources=cuda_src,
41
+ functions=[p["func"]],
42
+ verbose=False,
43
+ )
44
+
45
+
46
+ def compare(ref, out):
47
+ if not isinstance(out, torch.Tensor):
48
+ return dict(status="killed", reason="not_a_tensor")
49
+ if out.shape != ref.shape:
50
+ return dict(status="killed", reason="shape_mismatch",
51
+ detail=f"{tuple(out.shape)} vs {tuple(ref.shape)}")
52
+ ok = torch.allclose(ref, out, atol=ATOL, rtol=RTOL)
53
+ if ok:
54
+ return dict(status="survived")
55
+ diff = (ref - out).abs()
56
+ finite = torch.isfinite(out).all().item()
57
+ return dict(status="killed", reason="value_mismatch",
58
+ max_diff=float(diff.nan_to_num(nan=float("inf")).max()),
59
+ out_finite=bool(finite))
60
+
61
+
62
+ def main():
63
+ problem, journal_path = sys.argv[1], sys.argv[2]
64
+ p = K.PROBLEMS[problem]
65
+
66
+ done = {} # (variant, suite) -> True
67
+ crashed = set() # variants that crashed a previous process
68
+ pending_start = None
69
+ if os.path.exists(journal_path):
70
+ for line in open(journal_path):
71
+ rec = json.loads(line)
72
+ if rec["type"] == "START":
73
+ pending_start = (rec["variant"], rec["suite"])
74
+ elif rec["type"] == "RESULT":
75
+ done[(rec["variant"], rec["suite"])] = True
76
+ pending_start = None
77
+
78
+ journal = open(journal_path, "a")
79
+
80
+ def emit(rec):
81
+ journal.write(json.dumps(rec) + "\n")
82
+ journal.flush()
83
+ os.fsync(journal.fileno())
84
+
85
+ # a START without RESULT means the previous process died on that (variant, suite)
86
+ if pending_start is not None:
87
+ v, s = pending_start
88
+ emit(dict(type="RESULT", variant=v, suite=s, trial=-1,
89
+ status="killed", reason="process_crash"))
90
+ done[(v, s)] = True
91
+ crashed.add(v)
92
+
93
+ ref_model, _ = load_ref_model(problem)
94
+ ref_model = ref_model.cuda().eval()
95
+ suites = p["suites"]()
96
+
97
+ # cache reference outputs on CPU: (suite, trial) -> ref_out
98
+ ref_cache = {}
99
+
100
+ def ref_out_for(suite_name, builder, trial):
101
+ key = (suite_name, trial)
102
+ if key not in ref_cache:
103
+ inputs = builder(trial)
104
+ with torch.no_grad():
105
+ gpu_in = [t.cuda() for t in inputs]
106
+ ref_cache[key] = ref_model(*gpu_in).cpu()
107
+ del gpu_in
108
+ torch.cuda.empty_cache()
109
+ return ref_cache[key]
110
+
111
+ for variant_id, cuda_src in K.all_variants(problem):
112
+ if variant_id in crashed:
113
+ for suite_name, _, _ in suites:
114
+ if (variant_id, suite_name) not in done:
115
+ emit(dict(type="RESULT", variant=variant_id, suite=suite_name, trial=-1,
116
+ status="skipped_after_crash"))
117
+ continue
118
+
119
+ try:
120
+ ext = build_ext(problem, variant_id, cuda_src)
121
+ except Exception as e:
122
+ for suite_name, _, _ in suites:
123
+ if (variant_id, suite_name) not in done:
124
+ emit(dict(type="RESULT", variant=variant_id, suite=suite_name, trial=-1,
125
+ status="killed", reason="compile_error", detail=str(e)[:300]))
126
+ continue
127
+
128
+ wrapper_cls = p["wrapper"]
129
+ if problem == "sum":
130
+ model_new = wrapper_cls(ext, 1)
131
+ else:
132
+ model_new = wrapper_cls(ext)
133
+ model_new = model_new.cuda().eval()
134
+
135
+ variant_dead = False
136
+ for suite_name, n_trials, builder in suites:
137
+ if (variant_id, suite_name) in done:
138
+ continue
139
+ if variant_dead:
140
+ emit(dict(type="RESULT", variant=variant_id, suite=suite_name, trial=-1,
141
+ status="skipped_after_crash"))
142
+ continue
143
+ emit(dict(type="START", variant=variant_id, suite=suite_name))
144
+ result = dict(status="survived")
145
+ for trial in range(n_trials):
146
+ ref_out = ref_out_for(suite_name, builder, trial)
147
+ inputs = builder(trial)
148
+ try:
149
+ with torch.no_grad():
150
+ gpu_in = [t.cuda() for t in inputs]
151
+ out = model_new(*gpu_in)
152
+ torch.cuda.synchronize()
153
+ r = compare(ref_out.cuda(), out)
154
+ del gpu_in, out
155
+ torch.cuda.empty_cache()
156
+ except RuntimeError as e:
157
+ r = dict(status="killed", reason="runtime_error", detail=str(e)[:300])
158
+ if "CUDA" in str(e) or "cuda" in str(e):
159
+ # context may be poisoned; record and let the driver restart us
160
+ r["trial"] = trial
161
+ emit(dict(type="RESULT", variant=variant_id, suite=suite_name, **r))
162
+ journal.close()
163
+ sys.exit(3)
164
+ if r["status"] == "killed":
165
+ r["trial"] = trial
166
+ result = r
167
+ break
168
+ if "trial" not in result:
169
+ result["trial"] = n_trials
170
+ emit(dict(type="RESULT", variant=variant_id, suite=suite_name, **result))
171
+
172
+ emit(dict(type="DONE", problem=problem))
173
+ journal.close()
174
+
175
+
176
+ if __name__ == "__main__":
177
+ main()
pipeline/find_substrate.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ import glob, sys
2
+ p = sys.argv[1]
3
+ cands = glob.glob('substrates/accepted/candidate_*.py') + ['problems_ext.py', 'problems_batch2.py']
4
+ for f in cands:
5
+ try: s = open(f).read()
6
+ except OSError: continue
7
+ if f'"{p}"' in s or f"'{p}'" in s:
8
+ print(f); break
pipeline/forkpool.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fork-based crash isolation with a preloaded registry.
2
+
3
+ Problem: importing the 188-substrate registry costs ~85s, and a mutant that
4
+ triggers an illegal memory access poisons the CUDA context so unrecoverably
5
+ that the process must exit. Paying the import per problem (for isolation) wastes
6
+ most of the runtime.
7
+
8
+ Solution: the PARENT loads the registry once and never touches CUDA. For each
9
+ unit of work it fork()s a child; the child inherits the registry through
10
+ copy-on-write (no reload, no serialization), initializes CUDA itself, does the
11
+ work, and exits. If the child dies — poisoned context, watchdog kill, OOM —
12
+ the parent is unaffected and forks the next one.
13
+
14
+ Constraint: the parent must NOT initialize CUDA (a CUDA context cannot be
15
+ inherited across fork), so keep all torch.cuda calls inside run_fn.
16
+ """
17
+ import os
18
+ import sys
19
+
20
+
21
+ def run_isolated(run_fn, *args, timeout=None):
22
+ """Run run_fn(*args) in a forked child. Returns the child's exit code.
23
+
24
+ 0 = completed; 3 = the runner's "context poisoned, respawn me" signal;
25
+ other = crash/kill. The parent never shares CUDA state with the child.
26
+ """
27
+ pid = os.fork()
28
+ if pid == 0: # child
29
+ code = 0
30
+ try:
31
+ run_fn(*args)
32
+ except SystemExit as e:
33
+ code = e.code if isinstance(e.code, int) else 1
34
+ except Exception:
35
+ import traceback
36
+ traceback.print_exc()
37
+ code = 1
38
+ finally:
39
+ sys.stdout.flush()
40
+ sys.stderr.flush()
41
+ os._exit(code) # never run parent's atexit/finalizers
42
+ if timeout is None:
43
+ _, status = os.waitpid(pid, 0)
44
+ return os.waitstatus_to_exitcode(status)
45
+ # bounded wait: kill the child if it exceeds the wall-clock budget
46
+ import time
47
+ deadline = time.monotonic() + timeout
48
+ while True:
49
+ done, status = os.waitpid(pid, os.WNOHANG)
50
+ if done:
51
+ return os.waitstatus_to_exitcode(status)
52
+ if time.monotonic() > deadline:
53
+ os.kill(pid, 9)
54
+ os.waitpid(pid, 0)
55
+ return 124
56
+ time.sleep(0.5)
57
+
58
+
59
+ def isolated_loop(problems, run_fn, label="run", timeout=2400, retries=6):
60
+ """Process problems one at a time, each in its own forked child.
61
+
62
+ The registry stays resident in the parent, so a crash costs only the work
63
+ in flight — never a re-import.
64
+ """
65
+ for p in problems:
66
+ for attempt in range(retries):
67
+ rc = run_isolated(run_fn, p, timeout=timeout)
68
+ if rc == 0:
69
+ break
70
+ if rc == 124:
71
+ print(f"[{label}] {p}: TIMEOUT (child killed)", flush=True)
72
+ break
73
+ print(f"[{label}] {p}: done", flush=True)
pipeline/full_matrix.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Full kill matrix: every non-trivial mutant x every targeted suite, no early exit.
2
+
3
+ Uses the screening journals to scope work:
4
+ - mutants classified killed_by_T0 (value kill), high_value, no_witness are
5
+ evaluated against EVERY targeted suite (T0 outcome is already known);
6
+ - mutants that killed via crash (reason=crash / probe_crash) are excluded
7
+ from re-execution — their journal witness stands in for their kill vector.
8
+
9
+ Output: results/matrix_<problem>.jsonl lines
10
+ {"type":"CELL","id":...,"suite":...,"outcome":"killed"/"survived"[,"reason"]}
11
+ Crash-safe with the same START/respawn pattern as screening.
12
+
13
+ Usage: python3 full_matrix.py # orchestrator
14
+ python3 full_matrix.py --worker P # one problem
15
+ """
16
+ import ctypes
17
+ import json
18
+ import os
19
+ import subprocess
20
+ import sys
21
+
22
+ HERE = os.path.dirname(os.path.abspath(__file__))
23
+ sys.path.insert(0, HERE)
24
+ RESULTS = os.path.join(HERE, "results")
25
+
26
+ import kernels_def as K # noqa: E402
27
+ import problems_ext # noqa: E402,F401
28
+ import mutator # noqa: E402
29
+ from suite_filter import valid_suites # noqa: E402
30
+ from nvrtc_tce import externc, compile_ptx, device_source, normalized_hash # noqa: E402
31
+ from screen_mutants import (install_watchdog, pet_watchdog, NvrtcKernel, # noqa: E402
32
+ compare, kernel_name, launch_spec, ref_fn_for)
33
+
34
+
35
+ SHARD_ID = int(os.environ.get("SHARD_ID", "0"))
36
+ SHARD_N = int(os.environ.get("SHARD_N", "1"))
37
+
38
+
39
+ STEAL = os.environ.get("STEAL", "0") == "1"
40
+
41
+
42
+ def my_problems():
43
+ """Own hash slice, or (STEAL=1) any problem without an MDONE marker, so an
44
+ idle GPU helps finish the tail. Claim files keep two stealers off the same
45
+ problem; duplicate work would still be safe (journals dedupe by cell)."""
46
+ import hashlib
47
+ if STEAL:
48
+ out = []
49
+ for p in K.PROBLEMS:
50
+ jp = os.path.join(RESULTS, f"matrix_{p}.jsonl")
51
+ if os.path.exists(jp) and "MDONE" in open(jp).read():
52
+ continue
53
+ claim = os.path.join(RESULTS, f".mclaim_{p}")
54
+ try:
55
+ fd = os.open(claim, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
56
+ os.close(fd)
57
+ out.append(p)
58
+ except FileExistsError:
59
+ continue
60
+ return out
61
+ return [p for p in K.PROBLEMS
62
+ if int(hashlib.md5(p.encode()).hexdigest()[:8], 16) % SHARD_N == SHARD_ID]
63
+
64
+
65
+ def screening_classes(problem):
66
+ path = os.path.join(RESULTS, f"screen_{problem}.jsonl")
67
+ res = {}
68
+ if not os.path.exists(path):
69
+ return res # problem not screened yet (e.g. newly added substrate)
70
+ for line in open(path):
71
+ r = json.loads(line)
72
+ if r["type"] == "RESULT":
73
+ res[r["id"]] = r
74
+ return res
75
+
76
+
77
+ def worker(problem):
78
+ install_watchdog()
79
+ import torch
80
+ cls = screening_classes(problem)
81
+ todo_ids = {i for i, r in cls.items()
82
+ if r["cls"] in ("killed_by_T0", "high_value", "no_witness")
83
+ and r.get("reason") not in ("crash", "probe_crash", "cuda_poisoned")}
84
+
85
+ jpath = os.path.join(RESULTS, f"matrix_{problem}.jsonl")
86
+ done, pending = set(), None
87
+ if os.path.exists(jpath):
88
+ for line in open(jpath):
89
+ r = json.loads(line)
90
+ if r["type"] == "START":
91
+ pending = (r["id"], r["suite"])
92
+ elif r["type"] == "CELL":
93
+ done.add((r["id"], r["suite"]))
94
+ pending = None
95
+ journal = open(jpath, "a")
96
+
97
+ def emit(**rec):
98
+ journal.write(json.dumps(rec) + "\n")
99
+ journal.flush()
100
+ os.fsync(journal.fileno())
101
+
102
+ if pending is not None:
103
+ emit(type="CELL", id=pending[0], suite=pending[1],
104
+ outcome="killed", reason="crash")
105
+ done.add(pending)
106
+
107
+ _ms = list(mutator.generate(problem, device_source(K.PROBLEMS[problem]["cuda"])))
108
+ _cap = int(os.environ.get("MUTANT_CAP", "0"))
109
+ if _cap:
110
+ _ms = mutator.stratified_sample(_ms, _cap) # same sample as screening
111
+ mutants = {m["id"]: m for m in _ms}
112
+ suites = [(n, min(t, 1), b) for n, t, b in valid_suites(problem)
113
+ if n != "T0_original"]
114
+
115
+ # suite-major order so only ONE suite's inputs live on the GPU at a time
116
+ # (fits 24GB cards); reference outputs stay on CPU and comparison runs there.
117
+ remaining = [(mid, sname) for sname, _, _ in suites for mid in sorted(todo_ids)
118
+ if (mid, sname) not in done]
119
+ if not remaining:
120
+ emit(type="MDONE", problem=problem)
121
+ return
122
+
123
+ torch.zeros(1, device="cuda")
124
+ cuda_lib = ctypes.CDLL("libcuda.so.1")
125
+ ref_fn = ref_fn_for(problem)
126
+ cache = {}
127
+
128
+ def get_pair(sname, builder):
129
+ if sname not in cache:
130
+ cache.clear()
131
+ torch.cuda.empty_cache()
132
+ gpu_in = [t.cuda() for t in builder(0)]
133
+ with torch.no_grad():
134
+ ref = ref_fn(*gpu_in) # keep on GPU: CPU round-trips dominated runtime
135
+ cache[sname] = (gpu_in, ref)
136
+ return cache[sname]
137
+
138
+ suite_map = {n: b for n, _, b in suites}
139
+ ptx_cache = {}
140
+ for mid, sname in remaining:
141
+ if mid not in ptx_cache:
142
+ src = externc(mutants[mid]["src"])
143
+ ptx_cache[mid] = compile_ptx(src, "m.cu")
144
+ emit(type="START", id=mid, suite=sname)
145
+ kern = NvrtcKernel(cuda_lib, ptx_cache[mid], kernel_name(problem))
146
+ try:
147
+ gpu_in, ref = get_pair(sname, suite_map[sname])
148
+ pet_watchdog()
149
+ out = kern.launch(problem, gpu_in, torch)
150
+ r = compare(ref, out, torch)
151
+ del out
152
+ torch.cuda.empty_cache()
153
+ kern.unload()
154
+ except RuntimeError as e:
155
+ emit(type="CELL", id=mid, suite=sname, outcome="killed",
156
+ reason="crash", detail=str(e)[:80])
157
+ journal.close()
158
+ sys.exit(3)
159
+ emit(type="CELL", id=mid, suite=sname,
160
+ outcome="survived" if r == "survived" else "killed")
161
+ emit(type="MDONE", problem=problem)
162
+
163
+
164
+ def orchestrate():
165
+ """Fork-per-problem: substrate registry loaded once in the parent."""
166
+ from forkpool import run_isolated
167
+ for problem in my_problems():
168
+ for attempt in range(120):
169
+ rc = run_isolated(worker, problem, timeout=2700)
170
+ if rc in (0, 124):
171
+ break
172
+ print(f"[matrix] {problem}: done", flush=True)
173
+ print("[matrix] ALL DONE", flush=True)
174
+
175
+
176
+ if __name__ == "__main__":
177
+ if len(sys.argv) > 2 and sys.argv[1] == "--worker":
178
+ worker(sys.argv[2])
179
+ else:
180
+ orchestrate()
pipeline/gate_candidates.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """GPU admission gate for substrate candidates.
2
+
3
+ Loads substrates/candidate_*.py (pending), validates each against the OFFICIAL
4
+ torch reference on all its suites (T0 capped at 2 trials) plus probes.
5
+ Passers move to substrates/accepted/ (auto-loaded thereafter); failures stay
6
+ pending with a report line — never admitted.
7
+ """
8
+ import ctypes
9
+ import json
10
+ import os
11
+ import shutil
12
+ import sys
13
+
14
+ HERE = os.path.dirname(os.path.abspath(__file__))
15
+ sys.path.insert(0, HERE)
16
+ RESULTS = os.path.join(HERE, "results")
17
+
18
+ import torch # noqa: E402
19
+
20
+ import candidates_loader # noqa: E402
21
+ import kernels_def as K # noqa: E402
22
+ import problems_ext # noqa: E402,F401
23
+ from nvrtc_tce import externc, compile_ptx, device_source # noqa: E402
24
+ from screen_mutants import NvrtcKernel, kernel_name, launch_spec, ref_fn_for # noqa: E402
25
+
26
+ ATOL = RTOL = 1e-2
27
+
28
+
29
+ def check(problem):
30
+ src = externc(device_source(K.PROBLEMS[problem]["cuda"]))
31
+ try:
32
+ ptx = compile_ptx(src, f"{problem}.cu")
33
+ except RuntimeError as e:
34
+ return False, f"nvrtc_fail: {str(e)[:120]}"
35
+ cuda_lib = ctypes.CDLL("libcuda.so.1")
36
+ kern = NvrtcKernel(cuda_lib, ptx, kernel_name(problem))
37
+ ref_fn = ref_fn_for(problem)
38
+ try:
39
+ for sname, n_trials, builder in K.PROBLEMS[problem]["suites"]():
40
+ for trial in range(min(n_trials, 2)):
41
+ gpu_in = [t.cuda() for t in builder(trial)]
42
+ with torch.no_grad():
43
+ ref = ref_fn(*gpu_in)
44
+ out = kern.launch(problem, gpu_in, torch)
45
+ if out.shape != ref.shape:
46
+ return False, f"{sname}/t{trial}: shape {tuple(out.shape)} vs {tuple(ref.shape)}"
47
+ if out.dtype.is_floating_point:
48
+ ok = torch.allclose(ref, out, atol=ATOL, rtol=RTOL)
49
+ else:
50
+ ok = bool((ref == out).all())
51
+ if not ok:
52
+ diff = (ref.float() - out.float()).abs().nan_to_num(nan=float("inf"))
53
+ return False, f"{sname}/t{trial}: value max_diff={float(diff.max()):.4g}"
54
+ del gpu_in, ref, out
55
+ torch.cuda.empty_cache()
56
+ except RuntimeError as e:
57
+ return False, f"runtime: {str(e)[:120]}"
58
+ finally:
59
+ kern.unload()
60
+ return True, "ok"
61
+
62
+
63
+ def main():
64
+ torch.zeros(1, device="cuda")
65
+ os.makedirs(os.path.join(HERE, "substrates", "accepted"), exist_ok=True)
66
+ added = candidates_loader.load_pending()
67
+ report = []
68
+ for problem in added:
69
+ ok, detail = check(problem)
70
+ report.append(dict(problem=problem, admitted=ok, detail=detail))
71
+ print(f"[gate] {problem:14s} {'ADMIT' if ok else 'REJECT'} {detail}",
72
+ flush=True)
73
+ if ok:
74
+ src = os.path.join(HERE, "substrates", f"candidate_{problem}.py")
75
+ if os.path.exists(src):
76
+ shutil.move(src, os.path.join(HERE, "substrates", "accepted",
77
+ f"candidate_{problem}.py"))
78
+ with open(os.path.join(RESULTS, "gate_report.json"), "w") as f:
79
+ json.dump(report, f, indent=1)
80
+ n_ok = sum(1 for r in report if r["admitted"])
81
+ print(f"[gate] admitted {n_ok}/{len(report)}", flush=True)
82
+
83
+
84
+ if __name__ == "__main__":
85
+ main()
pipeline/kernels_def.py ADDED
@@ -0,0 +1,437 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Definitions: 4 correct CUDA kernels for KernelBench problems, their mutants,
2
+ and test suites (original KernelBench inputs + targeted inputs).
3
+
4
+ Mutants are string substitutions on the CUDA source (universalmutator-style),
5
+ covering categories: boundary/guard, indexing, sync, precision, semantic.
6
+ """
7
+ import os
8
+ import torch
9
+ import torch.nn as nn
10
+
11
+ KB_ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "KernelBench", "KernelBench")
12
+
13
+ # ---------------------------------------------------------------- ReLU (level1/19)
14
+
15
+ RELU_CUDA = r"""
16
+ #include <torch/extension.h>
17
+ #include <cuda_runtime.h>
18
+ #include <cuda_fp16.h>
19
+
20
+ __global__ void relu_kernel(const float* x, float* out, long long n) {
21
+ long long idx = (long long)blockIdx.x * blockDim.x + threadIdx.x;
22
+ if (idx < n) { float val = x[idx]; out[idx] = fmaxf(val, 0.0f); }
23
+ }
24
+
25
+ torch::Tensor relu_cuda(torch::Tensor x) {
26
+ auto xc = x.contiguous();
27
+ auto out = torch::zeros_like(xc);
28
+ long long n = xc.numel();
29
+ const int block = 256;
30
+ long long grid = (n + block - 1) / block;
31
+ relu_kernel<<<(unsigned int)grid, block>>>(xc.data_ptr<float>(), out.data_ptr<float>(), n);
32
+ return out;
33
+ }
34
+ """
35
+ RELU_CPP = "torch::Tensor relu_cuda(torch::Tensor x);"
36
+
37
+ RELU_MUTANTS = [
38
+ dict(id="R1", category="semantic", desc="remove ReLU: fmaxf(val,0) -> val",
39
+ subs=[("fmaxf(val, 0.0f)", "val")]),
40
+ dict(id="R2", category="boundary", desc="remove idx<n guard (OOB write)",
41
+ subs=[("if (idx < n) { float val", "{ float val")]),
42
+ dict(id="R3", category="boundary", desc="grid ceil-div -> floor-div (tail not computed)",
43
+ subs=[("(n + block - 1) / block", "n / block")]),
44
+ dict(id="R4", category="boundary", desc="guard < -> <= (single OOB element)",
45
+ subs=[("if (idx < n)", "if (idx <= n)")]),
46
+ dict(id="R5", category="semantic", desc="fmaxf -> fminf (sanity: should be killed)",
47
+ subs=[("fmaxf(val, 0.0f)", "fminf(val, 0.0f)")]),
48
+ dict(id="R6", category="precision", desc="fp16 roundtrip on output",
49
+ subs=[("out[idx] = fmaxf(val, 0.0f);",
50
+ "out[idx] = __half2float(__float2half(fmaxf(val, 0.0f)));")]),
51
+ dict(id="R7", category="indexing", desc="threadIdx.x -> threadIdx.y (GPU-specific op)",
52
+ subs=[("blockDim.x + threadIdx.x;", "blockDim.x + threadIdx.y;")]),
53
+ ]
54
+
55
+ # ------------------------------------------------------------ MatMul (level1/1)
56
+
57
+ MATMUL_CUDA = r"""
58
+ #include <torch/extension.h>
59
+ #include <cuda_runtime.h>
60
+ #include <cuda_fp16.h>
61
+
62
+ #define TILE 32
63
+
64
+ __global__ void matmul_kernel(const float* A, const float* B, float* C, int N) {
65
+ __shared__ float As[TILE][TILE];
66
+ __shared__ float Bs[TILE][TILE];
67
+ int row = blockIdx.y * TILE + threadIdx.y;
68
+ int col = blockIdx.x * TILE + threadIdx.x;
69
+ float acc = 0.0f;
70
+ int numTiles = (N + TILE - 1) / TILE;
71
+ for (int t = 0; t < numTiles; t++) {
72
+ int a_col = t * TILE + threadIdx.x;
73
+ int b_row = t * TILE + threadIdx.y;
74
+ As[threadIdx.y][threadIdx.x] = (row < N && a_col < N) ? A[row * N + a_col] : 0.0f;
75
+ Bs[threadIdx.y][threadIdx.x] = (b_row < N && col < N) ? B[b_row * N + col] : 0.0f;
76
+ __syncthreads(); // sync-after-load
77
+ for (int k = 0; k < TILE; k++) {
78
+ acc += As[threadIdx.y][k] * Bs[k][threadIdx.x];
79
+ }
80
+ __syncthreads(); // sync-after-compute
81
+ }
82
+ if (row < N && col < N) { C[row * N + col] = acc; }
83
+ }
84
+
85
+ torch::Tensor matmul_cuda(torch::Tensor A, torch::Tensor B) {
86
+ auto Ac = A.contiguous(); auto Bc = B.contiguous();
87
+ int N = Ac.size(0);
88
+ auto C = torch::zeros({N, N}, Ac.options());
89
+ dim3 block(TILE, TILE);
90
+ dim3 grid((N + TILE - 1) / TILE, (N + TILE - 1) / TILE);
91
+ matmul_kernel<<<grid, block>>>(Ac.data_ptr<float>(), Bc.data_ptr<float>(), C.data_ptr<float>(), N);
92
+ return C;
93
+ }
94
+ """
95
+ MATMUL_CPP = "torch::Tensor matmul_cuda(torch::Tensor A, torch::Tensor B);"
96
+
97
+ MATMUL_MUTANTS = [
98
+ dict(id="M1", category="boundary", desc="remove tile-load edge guards",
99
+ subs=[("(row < N && a_col < N) ? A[row * N + a_col] : 0.0f", "A[row * N + a_col]"),
100
+ ("(b_row < N && col < N) ? B[b_row * N + col] : 0.0f", "B[b_row * N + col]")]),
101
+ dict(id="M2", category="boundary", desc="numTiles ceil-div -> floor-div",
102
+ subs=[("int numTiles = (N + TILE - 1) / TILE;", "int numTiles = N / TILE;")]),
103
+ dict(id="M3", category="sync", desc="remove __syncthreads after tile load",
104
+ subs=[("__syncthreads(); // sync-after-load", "// removed sync-after-load")]),
105
+ dict(id="M4", category="sync", desc="remove __syncthreads after compute",
106
+ subs=[("__syncthreads(); // sync-after-compute", "// removed sync-after-compute")]),
107
+ dict(id="M5", category="precision", desc="fp16 accumulator",
108
+ subs=[("float acc = 0.0f;", "__half acc = __float2half(0.0f);"),
109
+ ("acc += As[threadIdx.y][k] * Bs[k][threadIdx.x];",
110
+ "acc = __hadd(acc, __float2half(As[threadIdx.y][k] * Bs[k][threadIdx.x]));"),
111
+ ("C[row * N + col] = acc;", "C[row * N + col] = __half2float(acc);")]),
112
+ dict(id="M6", category="indexing", desc="transposed read of A tile (sanity: should be killed)",
113
+ subs=[("acc += As[threadIdx.y][k] * Bs[k][threadIdx.x];",
114
+ "acc += As[k][threadIdx.y] * Bs[k][threadIdx.x];")]),
115
+ dict(id="M7", category="semantic", desc="acc += -> acc = (sanity: should be killed)",
116
+ subs=[("acc += As[threadIdx.y][k]", "acc = As[threadIdx.y][k]")]),
117
+ dict(id="M8", category="boundary", desc="drop last K tile (t < numTiles-1)",
118
+ subs=[("t < numTiles; t++", "t < numTiles - 1; t++")]),
119
+ dict(id="M9", category="indexing", desc="swap blockIdx.x/blockIdx.y (GPU-specific op)",
120
+ subs=[("int row = blockIdx.y * TILE + threadIdx.y;", "int row = blockIdx.x * TILE + threadIdx.y;"),
121
+ ("int col = blockIdx.x * TILE + threadIdx.x;", "int col = blockIdx.y * TILE + threadIdx.x;")]),
122
+ ]
123
+
124
+ # ----------------------------------------------------------- Softmax (level1/23)
125
+
126
+ SOFTMAX_CUDA = r"""
127
+ #include <torch/extension.h>
128
+ #include <cuda_runtime.h>
129
+ #include <cuda_fp16.h>
130
+ #include <math_constants.h>
131
+
132
+ __global__ void softmax_kernel(const float* x, float* out, int dim) {
133
+ long long row = blockIdx.x;
134
+ const float* xr = x + row * dim;
135
+ float* outr = out + row * dim;
136
+ __shared__ float sdata[256];
137
+ int tid = threadIdx.x;
138
+ int iters = (dim + 255) / 256;
139
+
140
+ float local_max = -CUDART_INF_F;
141
+ for (int it = 0; it < iters; it++) {
142
+ int i = it * 256 + tid;
143
+ if (i < dim) { local_max = fmaxf(local_max, xr[i]); }
144
+ }
145
+ sdata[tid] = local_max;
146
+ __syncthreads(); // sync-max-store
147
+ for (int s = 128; s > 0; s >>= 1) { // max-reduce
148
+ if (tid < s) { sdata[tid] = fmaxf(sdata[tid], sdata[tid + s]); }
149
+ __syncthreads();
150
+ }
151
+ float row_max = sdata[0];
152
+ __syncthreads(); // sync-max-read
153
+
154
+ float local_sum = 0.0f;
155
+ for (int it = 0; it < iters; it++) {
156
+ int i = it * 256 + tid;
157
+ if (i < dim) { local_sum += expf(xr[i] - row_max); }
158
+ }
159
+ sdata[tid] = local_sum;
160
+ __syncthreads(); // sync-sum-store
161
+ for (int s = 128; s > 0; s >>= 1) { // sum-reduce
162
+ if (tid < s) { sdata[tid] = sdata[tid] + sdata[tid + s]; }
163
+ __syncthreads();
164
+ }
165
+ float row_sum = sdata[0];
166
+ __syncthreads(); // sync-sum-read
167
+
168
+ for (int it = 0; it < iters; it++) {
169
+ int i = it * 256 + tid;
170
+ if (i < dim) { outr[i] = expf(xr[i] - row_max) / row_sum; }
171
+ }
172
+ }
173
+
174
+ torch::Tensor softmax_cuda(torch::Tensor x) {
175
+ auto xc = x.contiguous();
176
+ int batch = xc.size(0);
177
+ int dim = xc.size(1);
178
+ auto out = torch::zeros_like(xc);
179
+ softmax_kernel<<<batch, 256>>>(xc.data_ptr<float>(), out.data_ptr<float>(), dim);
180
+ return out;
181
+ }
182
+ """
183
+ SOFTMAX_CPP = "torch::Tensor softmax_cuda(torch::Tensor x);"
184
+
185
+ SOFTMAX_MUTANTS = [
186
+ dict(id="S1", category="precision", desc="no max subtraction (numerically unstable)",
187
+ subs=[("local_sum += expf(xr[i] - row_max);", "local_sum += expf(xr[i]);"),
188
+ ("outr[i] = expf(xr[i] - row_max) / row_sum;", "outr[i] = expf(xr[i]) / row_sum;")]),
189
+ dict(id="S2", category="semantic", desc="output all zeros (extreme cheat mutant)",
190
+ subs=[("outr[i] = expf(xr[i] - row_max) / row_sum;", "outr[i] = 0.0f;")]),
191
+ dict(id="S3", category="boundary", desc="iters ceil-div -> floor-div (tail elements dropped)",
192
+ subs=[("int iters = (dim + 255) / 256;", "int iters = dim / 256;")]),
193
+ dict(id="S4", category="precision", desc="fp16 accumulation of exp-sum",
194
+ subs=[("local_sum += expf(xr[i] - row_max);",
195
+ "local_sum = __half2float(__hadd(__float2half(local_sum), __float2half(expf(xr[i] - row_max))));")]),
196
+ dict(id="S5", category="semantic", desc="row max computed as row min",
197
+ subs=[("local_max = fmaxf(local_max, xr[i]);", "local_max = fminf(local_max, xr[i]);"),
198
+ ("sdata[tid] = fmaxf(sdata[tid], sdata[tid + s]);", "sdata[tid] = fminf(sdata[tid], sdata[tid + s]);")]),
199
+ dict(id="S6", category="boundary", desc="sum-reduce starts at s=64 (drops half of partials)",
200
+ subs=[("for (int s = 128; s > 0; s >>= 1) { // sum-reduce",
201
+ "for (int s = 64; s > 0; s >>= 1) { // sum-reduce")]),
202
+ dict(id="S7", category="sync", desc="remove __syncthreads before sum-reduce",
203
+ subs=[("__syncthreads(); // sync-sum-store", "// removed sync-sum-store")]),
204
+ ]
205
+
206
+ # ------------------------------------------------- Sum reduction (level1/47)
207
+
208
+ SUM_CUDA = r"""
209
+ #include <torch/extension.h>
210
+ #include <cuda_runtime.h>
211
+ #include <cuda_fp16.h>
212
+
213
+ __global__ void sum_dim1_kernel(const float* x, float* out, int B, int R, int C) {
214
+ int c = blockIdx.x * blockDim.x + threadIdx.x;
215
+ int b = blockIdx.y;
216
+ if (c >= C) return;
217
+ float acc = 0.0f;
218
+ for (int r = 0; r < R; r++) {
219
+ acc += x[(long long)b * R * C + (long long)r * C + c];
220
+ }
221
+ out[(long long)b * C + c] = acc;
222
+ }
223
+
224
+ torch::Tensor sum_dim1_cuda(torch::Tensor x) {
225
+ auto xc = x.contiguous();
226
+ int B = xc.size(0); int R = xc.size(1); int C = xc.size(2);
227
+ auto out = torch::zeros({B, 1, C}, xc.options());
228
+ const int block = 256;
229
+ dim3 grid((C + block - 1) / block, B);
230
+ sum_dim1_kernel<<<grid, block>>>(xc.data_ptr<float>(), out.data_ptr<float>(), B, R, C);
231
+ return out;
232
+ }
233
+ """
234
+ SUM_CPP = "torch::Tensor sum_dim1_cuda(torch::Tensor x);"
235
+
236
+ SUM_MUTANTS = [
237
+ dict(id="U1", category="precision", desc="fp16 accumulator",
238
+ subs=[("float acc = 0.0f;", "__half acc = __float2half(0.0f);"),
239
+ ("acc += x[(long long)b * R * C + (long long)r * C + c];",
240
+ "acc = __hadd(acc, __float2half(x[(long long)b * R * C + (long long)r * C + c]));"),
241
+ ("out[(long long)b * C + c] = acc;", "out[(long long)b * C + c] = __half2float(acc);")]),
242
+ dict(id="U2", category="boundary", desc="drop last row (r < R-1)",
243
+ subs=[("r < R; r++", "r < R - 1; r++")]),
244
+ dict(id="U3", category="boundary", desc="remove c>=C guard (OOB, C=4095 misaligned)",
245
+ subs=[("if (c >= C) return;", "")]),
246
+ dict(id="U4", category="boundary", desc="grid ceil-div -> floor-div over columns",
247
+ subs=[("dim3 grid((C + block - 1) / block, B);", "dim3 grid(C / block, B);")]),
248
+ dict(id="U5", category="boundary", desc="skip first row (r starts at 1)",
249
+ subs=[("for (int r = 0; r < R; r++)", "for (int r = 1; r < R; r++)")]),
250
+ dict(id="U6", category="indexing", desc="swap row/col strides (sanity: should be killed)",
251
+ subs=[("acc += x[(long long)b * R * C + (long long)r * C + c];",
252
+ "acc += x[(long long)b * R * C + (long long)c * C + r];")]),
253
+ ]
254
+
255
+ # ---------------------------------------------------------------- wrappers
256
+
257
+
258
+ class ReluNew(nn.Module):
259
+ def __init__(self, ext):
260
+ super().__init__()
261
+ self.ext = ext
262
+
263
+ def forward(self, x):
264
+ return self.ext.relu_cuda(x)
265
+
266
+
267
+ class MatmulNew(nn.Module):
268
+ def __init__(self, ext):
269
+ super().__init__()
270
+ self.ext = ext
271
+
272
+ def forward(self, A, B):
273
+ return self.ext.matmul_cuda(A, B)
274
+
275
+
276
+ class SoftmaxNew(nn.Module):
277
+ def __init__(self, ext):
278
+ super().__init__()
279
+ self.ext = ext
280
+
281
+ def forward(self, x):
282
+ return self.ext.softmax_cuda(x)
283
+
284
+
285
+ class SumNew(nn.Module):
286
+ def __init__(self, ext, dim=1):
287
+ super().__init__()
288
+ assert dim == 1
289
+ self.ext = ext
290
+
291
+ def forward(self, x):
292
+ return self.ext.sum_dim1_cuda(x)
293
+
294
+
295
+ # ---------------------------------------------------------------- test suites
296
+ # Each suite: (name, n_trials, builder(trial) -> list of input tensors (CPU)).
297
+ # T0_original replicates the KernelBench protocol: get_inputs() under 5 seeds.
298
+
299
+
300
+ def _seeded(seed):
301
+ torch.manual_seed(seed)
302
+
303
+
304
+ def relu_suites():
305
+ def t0(t):
306
+ _seeded(1000 + t)
307
+ return [torch.rand(4096, 393216)]
308
+
309
+ def t1(t):
310
+ _seeded(7)
311
+ return [torch.randn(4096, 393216)]
312
+
313
+ def t3(t):
314
+ _seeded(8)
315
+ return [torch.randn(127, 4097)]
316
+
317
+ return [("T0_original", 5, t0), ("T1_signed", 1, t1), ("T3_misaligned", 1, t3)]
318
+
319
+
320
+ def matmul_suites():
321
+ def t0(t):
322
+ _seeded(1000 + t)
323
+ return [torch.rand(4096, 4096), torch.rand(4096, 4096)]
324
+
325
+ def t1(t):
326
+ _seeded(7)
327
+ return [torch.randn(4096, 4096), torch.randn(4096, 4096)]
328
+
329
+ def t2(t):
330
+ _seeded(9)
331
+ return [torch.randn(4096, 4096) * 100.0, torch.randn(4096, 4096) * 100.0]
332
+
333
+ def t3(t):
334
+ _seeded(11)
335
+ return [torch.randn(1031, 1031), torch.randn(1031, 1031)]
336
+
337
+ def t4(t):
338
+ _seeded(13)
339
+ A = torch.rand(4096, 4096)
340
+ B = torch.rand(4096, 4096)
341
+ A[:, -32:] = 100.0
342
+ B[-32:, :] = 100.0
343
+ return [A, B]
344
+
345
+ return [("T0_original", 5, t0), ("T1_signed", 1, t1), ("T2_large", 1, t2),
346
+ ("T3_misaligned", 1, t3), ("T4_last_tile_spike", 1, t4)]
347
+
348
+
349
+ def softmax_suites():
350
+ def t0(t):
351
+ _seeded(1000 + t)
352
+ return [torch.rand(4096, 393216)]
353
+
354
+ def t2(t):
355
+ _seeded(9)
356
+ return [torch.randn(4096, 393216) * 100.0]
357
+
358
+ def t3(t):
359
+ _seeded(11)
360
+ x = torch.zeros(4096, 393216)
361
+ spike_cols = torch.randint(0, 393216, (4096,))
362
+ x[torch.arange(4096), spike_cols] = 20.0
363
+ return [x]
364
+
365
+ def t4(t):
366
+ _seeded(13)
367
+ x = torch.randn(64, 4099) * 0.01
368
+ x[:, -1] = 20.0
369
+ return [x]
370
+
371
+ return [("T0_original", 5, t0), ("T2_large", 1, t2),
372
+ ("T3_spiky", 1, t3), ("T4_tail_spike_misaligned", 1, t4)]
373
+
374
+
375
+ def sum_suites():
376
+ def t0(t):
377
+ _seeded(1000 + t)
378
+ return [torch.rand(128, 4096, 4095)]
379
+
380
+ def t1(t):
381
+ _seeded(7)
382
+ return [torch.randn(128, 4096, 4095)]
383
+
384
+ def t2(t):
385
+ _seeded(9)
386
+ return [torch.randn(128, 4096, 4095) * 1000.0]
387
+
388
+ def t4(t):
389
+ _seeded(13)
390
+ x = torch.rand(128, 4096, 4095)
391
+ x[:, 0, :] += 100.0
392
+ x[:, -1, :] += 100.0
393
+ return [x]
394
+
395
+ return [("T0_original", 5, t0), ("T1_signed", 1, t1), ("T2_large", 1, t2),
396
+ ("T4_edge_row_spike", 1, t4)]
397
+
398
+
399
+ PROBLEMS = {
400
+ "relu": dict(
401
+ kb_file=os.path.join(KB_ROOT, "level1", "19_ReLU.py"),
402
+ cuda=RELU_CUDA, cpp=RELU_CPP, func="relu_cuda",
403
+ mutants=RELU_MUTANTS, wrapper=ReluNew, suites=relu_suites,
404
+ ),
405
+ "matmul": dict(
406
+ kb_file=os.path.join(KB_ROOT, "level1", "1_Square_matrix_multiplication_.py"),
407
+ cuda=MATMUL_CUDA, cpp=MATMUL_CPP, func="matmul_cuda",
408
+ mutants=MATMUL_MUTANTS, wrapper=MatmulNew, suites=matmul_suites,
409
+ ),
410
+ "softmax": dict(
411
+ kb_file=os.path.join(KB_ROOT, "level1", "23_Softmax.py"),
412
+ cuda=SOFTMAX_CUDA, cpp=SOFTMAX_CPP, func="softmax_cuda",
413
+ mutants=SOFTMAX_MUTANTS, wrapper=SoftmaxNew, suites=softmax_suites,
414
+ ),
415
+ "sum": dict(
416
+ kb_file=os.path.join(KB_ROOT, "level1", "47_Sum_reduction_over_a_dimension.py"),
417
+ cuda=SUM_CUDA, cpp=SUM_CPP, func="sum_dim1_cuda",
418
+ mutants=SUM_MUTANTS, wrapper=SumNew, suites=sum_suites,
419
+ ),
420
+ }
421
+
422
+
423
+ def mutated_source(problem, mutant):
424
+ src = PROBLEMS[problem]["cuda"]
425
+ for old, new in mutant["subs"]:
426
+ assert old in src, f"{problem}/{mutant['id']}: pattern not found: {old!r}"
427
+ src = src.replace(old, new)
428
+ assert src != PROBLEMS[problem]["cuda"], f"{problem}/{mutant['id']}: no-op mutation"
429
+ return src
430
+
431
+
432
+ def all_variants(problem):
433
+ """Yield (variant_id, cuda_source). 'correct' first, then mutants."""
434
+ p = PROBLEMS[problem]
435
+ yield "correct", p["cuda"]
436
+ for m in p["mutants"]:
437
+ yield m["id"], mutated_source(problem, m)
pipeline/mechanism_curves.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Two mechanism studies for the paper (§5), pure oracle analysis + one kernel.
2
+
3
+ Curve A — tolerance vacuity vs output magnitude:
4
+ softmax over increasing dim; at each dim, find the largest perturbation of
5
+ the reference output that still PASSES allclose(atol=rtol=1e-2). Shows the
6
+ oracle's blind band growing as outputs shrink (zeros pass for dim >~ 1/atol).
7
+
8
+ Curve B — legitimate-variance ceiling:
9
+ our correct tiled matmul vs torch.matmul at (2048x8192)x(8192x4096), input
10
+ magnitude sweep. Signed (randn*s) inputs cross the tolerance line (false
11
+ kill of a CORRECT kernel); positive (rand*s) never do. Quantifies the
12
+ input-aggressiveness ceiling and its fix.
13
+
14
+ Output: results/mechanism_curves.json + printed tables.
15
+ """
16
+ import ctypes
17
+ import json
18
+ import os
19
+ import sys
20
+
21
+ HERE = os.path.dirname(os.path.abspath(__file__))
22
+ sys.path.insert(0, HERE)
23
+ RESULTS = os.path.join(HERE, "results")
24
+
25
+ import torch # noqa: E402
26
+
27
+ import kernels_def as K # noqa: E402
28
+ import problems_ext # noqa: E402,F401
29
+ from nvrtc_tce import externc, compile_ptx, device_source # noqa: E402
30
+ from screen_mutants import NvrtcKernel, kernel_name # noqa: E402
31
+
32
+ ATOL = RTOL = 1e-2
33
+
34
+
35
+ def curve_vacuity():
36
+ rows = []
37
+ for dim in [64, 512, 4096, 32768, 262144, 393216]:
38
+ torch.manual_seed(1)
39
+ x = torch.rand(64, dim, device="cuda")
40
+ ref = torch.softmax(x, dim=1)
41
+ mag = float(ref.mean())
42
+ zeros_pass = bool(torch.allclose(ref, torch.zeros_like(ref),
43
+ atol=ATOL, rtol=RTOL))
44
+ # largest multiplicative error (1+delta) that still passes
45
+ lo, hi = 0.0, 1e4
46
+ for _ in range(40):
47
+ mid = (lo + hi) / 2
48
+ if torch.allclose(ref, ref * (1 + mid), atol=ATOL, rtol=RTOL):
49
+ lo = mid
50
+ else:
51
+ hi = mid
52
+ rows.append(dict(dim=dim, mean_output=mag, zeros_pass=zeros_pass,
53
+ max_undetected_rel_error=lo))
54
+ print(f"dim={dim:7d} mean_out={mag:.3g} zeros_pass={zeros_pass} "
55
+ f"max_undetected_rel_err={lo:.3g}", flush=True)
56
+ return rows
57
+
58
+
59
+ def curve_variance_ceiling():
60
+ """Uses the sum-reduction op: torch reduces pairwise, our kernel
61
+ sequentially — accumulation orders are guaranteed to differ, so the
62
+ legitimate fp32 variance between two CORRECT implementations is nonzero
63
+ and grows with input magnitude under cancellation. (On matmul at some
64
+ shapes cuBLAS happens to match our K-order bitwise — variance is
65
+ implementation-pair-specific, which is itself a finding.)"""
66
+ src = externc(device_source(K.PROBLEMS["sum"]["cuda"]))
67
+ ptx = compile_ptx(src, "sum.cu")
68
+ cuda_lib = ctypes.CDLL("libcuda.so.1")
69
+ kern = NvrtcKernel(cuda_lib, ptx, kernel_name("sum"))
70
+ rows = []
71
+ for dist in ("signed", "positive"):
72
+ for scale in [1, 3, 10, 30, 100, 300, 1000, 3000]:
73
+ torch.manual_seed(2)
74
+ x = torch.randn(128, 4096, 4095, device="cuda") * scale
75
+ if dist == "positive":
76
+ x = x.abs()
77
+ with torch.no_grad():
78
+ ref = torch.sum(x, dim=1, keepdim=True)
79
+ out = kern.launch("sum", [x], torch)
80
+ diff = (ref - out).abs()
81
+ thresh = ATOL + RTOL * out.abs()
82
+ margin = float((diff - thresh).max())
83
+ false_kill = bool((diff > thresh).any())
84
+ rows.append(dict(dist=dist, scale=scale, max_diff=float(diff.max()),
85
+ worst_margin=margin, false_kill=false_kill))
86
+ print(f"{dist:8s} scale={scale:5d} max_diff={float(diff.max()):.4g} "
87
+ f"false_kill={false_kill}", flush=True)
88
+ del x, ref, out, diff, thresh
89
+ torch.cuda.empty_cache()
90
+ kern.unload()
91
+ return rows
92
+
93
+
94
+ if __name__ == "__main__":
95
+ torch.zeros(1, device="cuda")
96
+ out = dict(vacuity=curve_vacuity(), variance_ceiling=curve_variance_ceiling())
97
+ with open(os.path.join(RESULTS, "mechanism_curves.json"), "w") as f:
98
+ json.dump(out, f, indent=1)
99
+ print("CURVES DONE", flush=True)
pipeline/mutator.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Universal mutator for CUDA device code.
2
+
3
+ Pattern-level rules (generalized from the 29 validated hand-written mutants)
4
+ are applied to arbitrary kernel source: each rule is a regex; each match site
5
+ yields one mutant (replace that single occurrence). Deterministic: same source
6
+ + same rules => same mutant set, ids stable.
7
+
8
+ Categories mirror the validated taxonomy: boundary, sync, precision,
9
+ indexing, arithmetic, semantic.
10
+ """
11
+ import re
12
+ from dataclasses import dataclass
13
+
14
+
15
+ @dataclass
16
+ class Rule:
17
+ name: str
18
+ category: str
19
+ pattern: str # regex, applied to device source
20
+ replacement: str # regex template (\1 etc.)
21
+ note: str = ""
22
+
23
+
24
+ RULES = [
25
+ # ---- boundary -------------------------------------------------------
26
+ Rule("ceil2floor", "boundary",
27
+ r"\(\s*(\w+)\s*\+\s*(\w+)\s*-\s*1\s*\)\s*/\s*\2",
28
+ r"\1 / \2",
29
+ "ceil-div -> floor-div: tail block never processed"),
30
+ Rule("ceil2floor-lit", "boundary",
31
+ r"\(\s*(\w+)\s*\+\s*(\d+)\s*\)\s*/\s*(\d+)",
32
+ r"\1 / \3",
33
+ "(x + K-1)/K with literal K -> floor"),
34
+ Rule("lt2le", "boundary",
35
+ r"(\w[\w\.\[\]]*) < (\w[\w\.\[\]]*)\)",
36
+ r"\1 <= \2)",
37
+ "guard/loop bound < -> <= : off-by-one overrun"),
38
+ Rule("le2lt", "boundary",
39
+ r"(\w[\w\.\[\]]*) <= (\w[\w\.\[\]]*)\)",
40
+ r"\1 < \2)",
41
+ "<= -> < : off-by-one underrun"),
42
+ Rule("ge2gt", "boundary",
43
+ r"(\w[\w\.\[\]]*) >= (\w[\w\.\[\]]*)\)",
44
+ r"\1 > \2)",
45
+ "early-return guard >= -> > : one OOB lane slips through"),
46
+ Rule("guard-drop-if", "boundary",
47
+ r"if \((\w+) < (\w+)\) ",
48
+ r"",
49
+ "remove single-line bounds guard entirely (silent OOB)"),
50
+ Rule("guard-drop-ternary", "boundary",
51
+ r"\(([^?\n]{1,80})\) \? ([^:\n]{1,80}) : 0\.0f",
52
+ r"\2",
53
+ "remove edge-tile ternary guard: unconditional load"),
54
+ Rule("loop-bound-minus1", "boundary",
55
+ r"; (\w+) < ([\w\.\[\]]+); \1\+\+",
56
+ r"; \1 < \2 - 1; \1++",
57
+ "drop last loop iteration (last tile / last row missing)"),
58
+ Rule("loop-start-1", "boundary",
59
+ r"for \(int (\w+) = 0;",
60
+ r"for (int \1 = 1;",
61
+ "skip first loop iteration"),
62
+ # ---- sync -----------------------------------------------------------
63
+ Rule("sync-remove", "sync",
64
+ r"__syncthreads\(\);",
65
+ r"",
66
+ "remove barrier: shared-memory race"),
67
+ # ---- precision ------------------------------------------------------
68
+ Rule("acc-fp16", "precision",
69
+ r"float (\w*(?:acc|sum)\w*) = 0\.0f;",
70
+ r"__half \1 = __float2half(0.0f); #define ACCH_\1",
71
+ "fp32 accumulator declared fp16 (paired by fixup below)"),
72
+ Rule("store-fp16", "precision",
73
+ r"(\w+)\[(\w[\w \+\*\.]*)\] = ([\w\(\)\[\]\.\+\-\*/, ]+);",
74
+ r"\1[\2] = __half2float(__float2half(\3));",
75
+ "output store through fp16 roundtrip"),
76
+ Rule("expf-fast", "precision",
77
+ r"expf\(",
78
+ r"__expf(",
79
+ "expf -> fast-math __expf approximation"),
80
+ Rule("fdividef-fast", "precision",
81
+ r"([\w\(\)\[\]\. ]+) / (\w*sum\w*)",
82
+ r"__fdividef(\1, \2)",
83
+ "true division -> fast approximate division"),
84
+ # ---- indexing (GPU-specific) ----------------------------------------
85
+ Rule("tidx2tidy", "indexing",
86
+ r"threadIdx\.x",
87
+ r"threadIdx.y",
88
+ "wrong thread axis"),
89
+ Rule("bidx2bidy", "indexing",
90
+ r"blockIdx\.x",
91
+ r"blockIdx.y",
92
+ "wrong block axis (single site, unlike consistent-swap)"),
93
+ Rule("bdim2gdim", "indexing",
94
+ r"blockDim\.x",
95
+ r"gridDim.x",
96
+ "blockDim -> gridDim in index math"),
97
+ # ---- arithmetic / semantic -----------------------------------------
98
+ Rule("plus2minus", "arithmetic",
99
+ r"(\w[\w\]\[\.]*) \+ (\w[\w\]\[\.]*)",
100
+ r"\1 - \2",
101
+ "AOR: + -> -"),
102
+ Rule("acc-overwrite", "semantic",
103
+ r"(\w+) \+= ",
104
+ r"\1 = ",
105
+ "accumulate -> overwrite (keeps last term only)"),
106
+ Rule("acc-minus", "semantic",
107
+ r"(\w+) \+= ",
108
+ r"\1 -= ",
109
+ "accumulate -> subtract"),
110
+ Rule("fmax2fmin", "semantic",
111
+ r"fmaxf\(",
112
+ r"fminf(",
113
+ "max -> min"),
114
+ Rule("fmin2fmax", "semantic",
115
+ r"fminf\(",
116
+ r"fmaxf(",
117
+ "min -> max"),
118
+ Rule("sentinel-zero", "semantic",
119
+ r"-CUDART_INF_F",
120
+ r"0.0f",
121
+ "reduction sentinel -inf -> 0 (breaks all-negative rows)"),
122
+ Rule("const0to1", "semantic",
123
+ r"= 0\.0f;",
124
+ r"= 1.0f;",
125
+ "init constant 0 -> 1"),
126
+ # ---- ROR completion --------------------------------------------------
127
+ Rule("lt2gt", "boundary",
128
+ r"(\w[\w\.\[\]]*) < (\w[\w\.\[\]]*)\)",
129
+ r"\1 > \2)",
130
+ "ROR: < -> > (inverted guard)"),
131
+ Rule("gt2ge", "boundary",
132
+ r"(\w[\w\.\[\]]*) > (\w[\w\.\[\]]*)\)",
133
+ r"\1 >= \2)",
134
+ "ROR: > -> >="),
135
+ Rule("return-guard-drop", "boundary",
136
+ r"if \((\w+) >= (\w+)\) return;",
137
+ r"",
138
+ "remove early-return bounds guard (silent OOB)"),
139
+ # ---- AOR completion --------------------------------------------------
140
+ Rule("mul2div", "arithmetic",
141
+ r"(\w[\w\]\[\.]*) \* (\w[\w\]\[\.]*)",
142
+ r"\1 / \2",
143
+ "AOR: * -> /"),
144
+ Rule("mul2plus", "arithmetic",
145
+ r"(\w[\w\]\[\.]*) \* (\w[\w\]\[\.]*)",
146
+ r"\1 + \2",
147
+ "AOR: * -> +"),
148
+ Rule("minus2plus", "arithmetic",
149
+ r"(\w[\w\]\[\.]*) - (\w[\w\]\[\.]*)",
150
+ r"\1 + \2",
151
+ "AOR: - -> +"),
152
+ Rule("negate-store", "arithmetic",
153
+ r"= (expf\([^;]+\));",
154
+ r"= -(\1);",
155
+ "UOI: negate stored expression"),
156
+ # ---- GPU-specific additions ------------------------------------------
157
+ Rule("sync2syncwarp", "sync",
158
+ r"__syncthreads\(\);",
159
+ r"__syncwarp();",
160
+ "block barrier -> warp barrier (insufficient sync, realistic bug)"),
161
+ Rule("reduce-shift2", "boundary",
162
+ r">>= 1\)",
163
+ r">>= 2)",
164
+ "tree reduction skips levels"),
165
+ Rule("smem-index-off1", "indexing",
166
+ r"\[(\w+) \+ (\w+)\]",
167
+ r"[\1 + \2 + 1]",
168
+ "shared-memory partner index off by one"),
169
+ Rule("warpsize-16", "indexing",
170
+ r"= (\d{2,3}) / 2;",
171
+ r"= \1 / 4;",
172
+ "reduction start half -> quarter"),
173
+ ]
174
+
175
+ # acc-fp16 needs paired rewrites of the += line and the final store; a single
176
+ # regex site can't do that, so it is expanded structurally here.
177
+
178
+
179
+ def _expand_fp16_acc(src, var):
180
+ out = src
181
+ out = out.replace(f"float {var} = 0.0f;", f"__half {var} = __float2half(0.0f);")
182
+ m = re.search(rf"{re.escape(var)} \+= ([^;]+);", out)
183
+ if not m:
184
+ return None
185
+ out = out.replace(m.group(0), f"{var} = __hadd({var}, __float2half({m.group(1)}));")
186
+ m2 = re.search(rf"= {re.escape(var)};", out)
187
+ if m2:
188
+ out = out.replace(m2.group(0), f"= __half2float({var});")
189
+ return out if out != src else None
190
+
191
+
192
+ def layer_of(src, pos):
193
+ """Which __global__ (i.e. which network layer) contains this offset?
194
+ Multi-kernel level-3 substrates hold one kernel per layer, so this labels
195
+ each mutant with its depth and lets us measure fault propagation."""
196
+ idx, kname = -1, "?"
197
+ for i, m in enumerate(re.finditer(r"__global__\s+void\s+(\w+)", src)):
198
+ if m.start() <= pos:
199
+ idx, kname = i, m.group(1)
200
+ else:
201
+ break
202
+ return idx, kname
203
+
204
+
205
+ def stratified_sample(mutants, cap, seed=0):
206
+ """Cap the pool per problem while preserving the (rule, layer) mix.
207
+
208
+ Level-3 substrates yield thousands of mutants per problem (one kernel per
209
+ layer); exhaustive screening is neither affordable nor necessary. We keep a
210
+ proportional share of every (rule, layer) stratum so the class distribution
211
+ — and every layer's representation — survives the cut.
212
+ """
213
+ import collections
214
+ import random
215
+ if len(mutants) <= cap:
216
+ return mutants
217
+ strata = collections.defaultdict(list)
218
+ for m in mutants:
219
+ strata[(m["rule"], m.get("layer", -1))].append(m)
220
+ rng = random.Random(seed)
221
+ keep, order = [], sorted(strata)
222
+ # one from every stratum first, so no rule or layer disappears
223
+ for k in order:
224
+ keep.append(strata[k][0])
225
+ remaining = cap - len(keep)
226
+ if remaining > 0:
227
+ rest = [m for k in order for m in strata[k][1:]]
228
+ rng.shuffle(rest)
229
+ keep.extend(rest[:remaining])
230
+ keep.sort(key=lambda m: m["id"])
231
+ return keep
232
+
233
+
234
+ def generate(name, src):
235
+ """Yield dicts: one mutant per (rule, match site). Deterministic order."""
236
+ seen_src = {src}
237
+ for rule in RULES:
238
+ if rule.name == "acc-fp16":
239
+ for m in re.finditer(r"float (\w*(?:acc|sum)\w*) = 0\.0f;", src):
240
+ mutated = _expand_fp16_acc(src, m.group(1))
241
+ if mutated and mutated not in seen_src:
242
+ seen_src.add(mutated)
243
+ li, lname = layer_of(src, m.start())
244
+ yield dict(id=f"{name}:acc-fp16:{m.start()}", rule=rule.name,
245
+ category=rule.category, site=m.group(1),
246
+ src=mutated, layer=li, layer_name=lname)
247
+ continue
248
+ for i, m in enumerate(re.finditer(rule.pattern, src)):
249
+ mutated = src[:m.start()] + m.expand(rule.replacement) + src[m.end():]
250
+ if "#define ACCH" in mutated: # acc-fp16 placeholder path, handled above
251
+ continue
252
+ if mutated == src or mutated in seen_src:
253
+ continue
254
+ seen_src.add(mutated)
255
+ snippet = " ".join(m.group(0).split())[:48]
256
+ li, lname = layer_of(src, m.start())
257
+ yield dict(id=f"{name}:{rule.name}:{i}", rule=rule.name,
258
+ category=rule.category, site=snippet, src=mutated,
259
+ layer=li, layer_name=lname)
260
+
261
+
262
+ if __name__ == "__main__":
263
+ import kernels_def as K
264
+ from nvrtc_tce import device_source
265
+ total = 0
266
+ for prob in K.PROBLEMS:
267
+ muts = list(generate(prob, device_source(K.PROBLEMS[prob]["cuda"])))
268
+ by_cat = {}
269
+ for mu in muts:
270
+ by_cat[mu["category"]] = by_cat.get(mu["category"], 0) + 1
271
+ print(f"{prob:8s}: {len(muts):4d} mutants {by_cat}")
272
+ total += len(muts)
273
+ print(f"total : {total}")
274
+
275
+
276
+ # ---- mined rules (LLM-designed, empirically validated; see rules/BRIEF.md) --
277
+ try:
278
+ import os as _os, sys as _sys
279
+ _sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))
280
+ from rules.mined_rules import MINED_RULES as _MINED
281
+ from rules.structural_rules import STRUCTURAL_RULES as _STRUCT
282
+ from rules.fine_rules import FINE_RULES as _FINE
283
+ _existing = {r.pattern for r in RULES}
284
+ for _r in list(_MINED) + list(_STRUCT) + list(_FINE):
285
+ if _r.pattern not in _existing:
286
+ RULES.append(_r); _existing.add(_r.pattern)
287
+ except Exception:
288
+ pass
pipeline/nvrtc_tce.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """NVRTC compile-time benchmark + TCE (Trivial Compiler Equivalence) dedup.
2
+
3
+ For every variant in kernels_def, extract the device code (the __global__
4
+ kernels, dropping the torch host wrapper), compile with NVRTC to PTX for
5
+ sm_90, time it, and hash the normalized PTX. Variants with identical PTX
6
+ hashes are trivially equivalent *at the device-code level* (note: mutants
7
+ that only touch the host-side launch config will collide with 'correct' —
8
+ in an NVRTC harness the launch config lives in Python and needs no nvcc).
9
+
10
+ Also does one end-to-end sanity run: loads the NVRTC-compiled correct ReLU
11
+ via the CUDA driver API and runs it on a torch tensor.
12
+ """
13
+ import ctypes
14
+ import ctypes.util
15
+ import hashlib
16
+ import re
17
+ import time
18
+
19
+ import kernels_def as K
20
+
21
+ nvrtc = ctypes.CDLL("libnvrtc.so.12")
22
+
23
+
24
+ def check(rc, what):
25
+ if rc != 0:
26
+ raise RuntimeError(f"{what} failed rc={rc}")
27
+
28
+
29
+ def compile_ptx(src, name="k.cu"):
30
+ prog = ctypes.c_void_p()
31
+ check(nvrtc.nvrtcCreateProgram(ctypes.byref(prog), src.encode(), name.encode(),
32
+ 0, None, None), "nvrtcCreateProgram")
33
+ import os as _os
34
+ arch = _os.environ.get("NVRTC_ARCH", "compute_90").encode()
35
+ # The driver (535.x = CUDA 12.2) rejects PTX emitted for newer toolkits
36
+ # with cuModuleLoadData rc=222; pin the PTX ISA to what it accepts.
37
+ # Driver 535.x (CUDA 12.2) refuses PTX emitted by the 12.6 NVRTC
38
+ # (cuModuleLoadData rc=222). Emitting CUBIN instead skips the driver's
39
+ # PTX JIT entirely: it is already SASS for this exact architecture.
40
+ use_cubin = _os.environ.get("NVRTC_CUBIN", "1") == "1"
41
+ if use_cubin:
42
+ arch = arch.replace(b"compute_", b"sm_")
43
+ opts = [b"--gpu-architecture=" + arch, b"-I/usr/local/cuda/include",
44
+ b"--std=c++17", b"-default-device"]
45
+ arr = (ctypes.c_char_p * len(opts))(*opts)
46
+ rc = nvrtc.nvrtcCompileProgram(prog, len(opts), arr)
47
+ logsz = ctypes.c_size_t()
48
+ nvrtc.nvrtcGetProgramLogSize(prog, ctypes.byref(logsz))
49
+ log = ctypes.create_string_buffer(logsz.value)
50
+ nvrtc.nvrtcGetProgramLog(prog, log)
51
+ if rc != 0:
52
+ nvrtc.nvrtcDestroyProgram(ctypes.byref(prog))
53
+ raise RuntimeError(f"nvrtc compile error:\n{log.value.decode()[:800]}")
54
+ sz = ctypes.c_size_t()
55
+ if use_cubin:
56
+ check(nvrtc.nvrtcGetCUBINSize(prog, ctypes.byref(sz)), "nvrtcGetCUBINSize")
57
+ buf = ctypes.create_string_buffer(sz.value)
58
+ check(nvrtc.nvrtcGetCUBIN(prog, buf), "nvrtcGetCUBIN")
59
+ nvrtc.nvrtcDestroyProgram(ctypes.byref(prog))
60
+ return buf.raw[:sz.value] # bytes: image for cuModuleLoadData
61
+ check(nvrtc.nvrtcGetPTXSize(prog, ctypes.byref(sz)), "nvrtcGetPTXSize")
62
+ buf = ctypes.create_string_buffer(sz.value)
63
+ check(nvrtc.nvrtcGetPTX(prog, buf), "nvrtcGetPTX")
64
+ nvrtc.nvrtcDestroyProgram(ctypes.byref(prog))
65
+ return buf.value.decode()
66
+
67
+
68
+ def externc(src):
69
+ """Give every __global__ C linkage so cuModuleGetFunction can find it by
70
+ name. Optimized kernels often write `__global__ __launch_bounds__(256) void
71
+ foo(...)`, so a plain "__global__ void" replacement misses them and the
72
+ symbol stays C++-mangled."""
73
+ import re as _re
74
+ return _re.sub(r'(?<!extern "C" )__global__(\s+(?:__launch_bounds__\s*\([^)]*\)\s*)?)',
75
+ r'extern "C" __global__\1', src)
76
+
77
+
78
+ def device_source(cuda_src):
79
+ """Keep everything up to the torch host wrapper; drop host-only includes."""
80
+ body = cuda_src.split("torch::Tensor")[0]
81
+ for inc in ("#include <torch/extension.h>", "#include <cuda_runtime.h>"):
82
+ body = body.replace(inc, "")
83
+ return body
84
+
85
+
86
+ def normalized_hash(image):
87
+ """TCE hash over the compiled image (PTX text or CUBIN bytes)."""
88
+ if isinstance(image, bytes):
89
+ return hashlib.sha256(image).hexdigest()[:16]
90
+ lines = [l for l in image.splitlines() if not l.strip().startswith("//")]
91
+ return hashlib.sha256("\n".join(lines).encode()).hexdigest()[:16]
92
+
93
+
94
+ def main():
95
+ rows = []
96
+ t_all = time.time()
97
+ for prob in K.PROBLEMS:
98
+ for vid, src in K.all_variants(prob):
99
+ dsrc = device_source(src)
100
+ t0 = time.time()
101
+ try:
102
+ ptx = compile_ptx(dsrc, f"{prob}_{vid}.cu")
103
+ dt = time.time() - t0
104
+ rows.append((prob, vid, dt, normalized_hash(ptx)))
105
+ except RuntimeError as e:
106
+ rows.append((prob, vid, time.time() - t0, f"COMPILE_FAIL: {e}"))
107
+ total = time.time() - t_all
108
+
109
+ print(f"== NVRTC compile times (sm_90), {len(rows)} variants, "
110
+ f"total {total:.2f}s ==")
111
+ times = [r[2] for r in rows if not str(r[3]).startswith("COMPILE_FAIL")]
112
+ print(f"per-variant: min {min(times)*1000:.0f}ms max {max(times)*1000:.0f}ms "
113
+ f"mean {sum(times)/len(times)*1000:.0f}ms")
114
+ print()
115
+ print("== TCE dedup (identical device PTX hash) ==")
116
+ by_hash = {}
117
+ for prob, vid, dt, h in rows:
118
+ by_hash.setdefault((prob, h), []).append(vid)
119
+ for (prob, h), vids in sorted(by_hash.items()):
120
+ if len(vids) > 1:
121
+ print(f" {prob}: {vids} <- identical device code (hash {h})")
122
+ print()
123
+ for prob, vid, dt, h in rows:
124
+ print(f" {prob:8s} {vid:8s} {dt*1000:6.0f}ms {h}")
125
+
126
+ # ---- end-to-end: run NVRTC-compiled correct ReLU on a torch tensor ----
127
+ print()
128
+ print("== end-to-end launch of NVRTC-compiled ReLU via driver API ==")
129
+ import torch
130
+ x = torch.randn(1_000_003, device="cuda") # deliberately misaligned size
131
+ out = torch.zeros_like(x)
132
+ torch.cuda.synchronize()
133
+
134
+ cuda = ctypes.CDLL("libcuda.so.1")
135
+ dsrc = device_source(K.PROBLEMS["relu"]["cuda"]).replace(
136
+ "__global__ void", 'extern "C" __global__ void')
137
+ ptx = compile_ptx(dsrc, "relu.cu")
138
+ module = ctypes.c_void_p()
139
+ check(cuda.cuModuleLoadData(ctypes.byref(module), ptx.encode()), "cuModuleLoadData")
140
+ func = ctypes.c_void_p()
141
+ check(cuda.cuModuleGetFunction(ctypes.byref(func), module, b"relu_kernel"),
142
+ "cuModuleGetFunction")
143
+
144
+ n = ctypes.c_longlong(x.numel())
145
+ xp = ctypes.c_void_p(x.data_ptr())
146
+ op = ctypes.c_void_p(out.data_ptr())
147
+ args = (ctypes.c_void_p * 3)(
148
+ ctypes.cast(ctypes.byref(xp), ctypes.c_void_p),
149
+ ctypes.cast(ctypes.byref(op), ctypes.c_void_p),
150
+ ctypes.cast(ctypes.byref(n), ctypes.c_void_p))
151
+ block = 256
152
+ grid = (x.numel() + block - 1) // block
153
+ check(cuda.cuLaunchKernel(func, grid, 1, 1, block, 1, 1, 0, None, args, None),
154
+ "cuLaunchKernel")
155
+ torch.cuda.synchronize()
156
+ ok = torch.equal(out, torch.relu(x))
157
+ print(f" launch ok, output matches torch.relu exactly: {ok}")
158
+
159
+
160
+ if __name__ == "__main__":
161
+ main()
pipeline/problems_batch2.py ADDED
@@ -0,0 +1,799 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Substrate batch 2: 14 more KernelBench level1 problems.
2
+
3
+ 8 activations (elementwise), 3 matmul variants, min-reduction, L1/L2 row norm.
4
+ Self-contained (no imports from problems_ext to avoid circular imports);
5
+ registered into kernels_def.PROBLEMS on import.
6
+ """
7
+ import ctypes
8
+
9
+ import torch as _torch
10
+
11
+ import kernels_def as K
12
+
13
+
14
+ def _seeded(seed):
15
+ _torch.manual_seed(seed)
16
+
17
+
18
+ # --------------------------------------------------------------- elementwise
19
+
20
+ _EW_TMPL = r"""
21
+ #include <cuda_fp16.h>
22
+
23
+ __global__ void {kname}(const float* x, float* out, long long n) {{
24
+ long long idx = (long long)blockIdx.x * blockDim.x + threadIdx.x;
25
+ if (idx < n) {{ float val = x[idx]; out[idx] = {expr}; }}
26
+ }}
27
+ """
28
+
29
+
30
+ def _ew_launch(inputs, torch):
31
+ x = inputs[0]
32
+ out = torch.zeros_like(x)
33
+ n = x.numel()
34
+ return out, ((n + 255) // 256, 1, 1), (256, 1, 1), [(ctypes.c_longlong, n)]
35
+
36
+
37
+ def _ew_suites():
38
+ def t0(t):
39
+ _seeded(1000 + t)
40
+ return [_torch.rand(4096, 393216)]
41
+
42
+ def t1(t):
43
+ _seeded(7)
44
+ return [_torch.randn(4096, 393216)]
45
+
46
+ def t2(t):
47
+ _seeded(9)
48
+ return [_torch.randn(4096, 393216) * 100.0]
49
+
50
+ def t3(t):
51
+ _seeded(8)
52
+ return [_torch.randn(127, 4097)]
53
+
54
+ return [("T0_original", 5, t0), ("T1_signed", 1, t1),
55
+ ("T2_large", 1, t2), ("T3_misaligned", 1, t3)]
56
+
57
+
58
+ def _swish_suites():
59
+ def t4(t):
60
+ _seeded(73)
61
+ x = _torch.full((31, 257), 65536.0, dtype=_torch.float32)
62
+ x[:, 0::4] = 65520.0
63
+ x[:, 1::4] = 65568.0
64
+ x[:, 2::4] = 70000.0
65
+ x[:, -1] = 131072.0
66
+ return [x]
67
+
68
+ def t5(t):
69
+ _seeded(79)
70
+ x = _torch.tensor([[1.0, 8.0, 64.0, 65520.0, 70000.0]],
71
+ dtype=_torch.float32)
72
+ return [x]
73
+
74
+ return _ew_suites() + [
75
+ ("T4_misaligned_fp16_overflow_stripes", 1, t4),
76
+ ("T5_small_partial_block_fp16_boundary", 1, t5),
77
+ ]
78
+
79
+
80
+ def _tanh_suites():
81
+ def t4(t):
82
+ _seeded(73)
83
+ x = _torch.full((1, 257), 8.0, dtype=_torch.float32)
84
+ x[:, 0::4] = 0.125
85
+ x[:, 1::4] = 0.54930615
86
+ x[:, 2::4] = 1.0986123
87
+ x[:, -1] = 16.0
88
+ return [x]
89
+
90
+ def t5(t):
91
+ _seeded(79)
92
+ values = _torch.tensor([
93
+ 0.010003, 0.031257, 0.062519, 0.125061,
94
+ 0.255413, 0.549306, 1.098612, 2.0,
95
+ 4.0, 8.0, 16.0,
96
+ ], dtype=_torch.float32)
97
+ x = values.repeat(23, 24)[:, :259]
98
+ x[:, -1] = 32.0
99
+ return [x]
100
+
101
+ return _ew_suites() + [
102
+ ("T4_misaligned_positive_tail_spike", 1, t4),
103
+ ("T5_positive_fp16_rounding_lattice", 1, t5),
104
+ ]
105
+
106
+
107
+ def _hardsigmoid_suites():
108
+ def t0(t):
109
+ _seeded(1000 + t)
110
+ return [_torch.rand(4096, 393216)]
111
+
112
+ def t1(t):
113
+ _seeded(7)
114
+ return [_torch.randn(4096, 393216)]
115
+
116
+ def t2(t):
117
+ _seeded(9)
118
+ return [_torch.randn(4096, 393216) * 100.0]
119
+
120
+ def t3(t):
121
+ _seeded(8)
122
+ return [_torch.randn(127, 4097)]
123
+
124
+ def t4(t):
125
+ _seeded(61)
126
+ values = _torch.tensor([
127
+ -3.001, -3.0, -2.999, -2.75, -2.0, -1.0,
128
+ -0.003, 0.0, 0.003, 1.0, 2.0, 2.75,
129
+ 2.999, 3.0, 3.001,
130
+ ], dtype=_torch.float32)
131
+ return [values.repeat(33, 18)[:, :257]]
132
+
133
+ def t5(t):
134
+ _seeded(67)
135
+ x = _torch.full((31, 257), 2.999, dtype=_torch.float32)
136
+ x[:, 0::4] = -2.999
137
+ x[:, 1::4] = -1.5015
138
+ x[:, 2::4] = 1.5015
139
+ x[:, -1] = 3000.0
140
+ return [x]
141
+
142
+ def t6(t):
143
+ _seeded(71)
144
+ outputs = (_torch.arange(255, dtype=_torch.float32) + 0.5) / 256.0
145
+ x = (outputs * 6.0 - 3.0).reshape(3, 85)
146
+ x[0, 0] = -3000.0
147
+ x[-1, -1] = 3000.0
148
+ return [x]
149
+
150
+ return [("T0_original", 5, t0), ("T1_signed", 1, t1),
151
+ ("T2_large", 1, t2), ("T3_misaligned", 1, t3),
152
+ ("T4_transition_threshold_stripes", 1, t4),
153
+ ("T5_misaligned_tail_spike", 1, t5),
154
+ ("T6_fp16_rounding_lattice", 1, t6)]
155
+
156
+
157
+ def _hardtanh_suites():
158
+ def t4(t):
159
+ _seeded(67)
160
+ x = _torch.full((33, 257), 2.0, dtype=_torch.float32)
161
+ x[:, 0::4] = 0.999
162
+ x[:, 1::4] = 1.0
163
+ x[:, 2::4] = 1.001
164
+ x[:, -1] = 64.0
165
+ return [x]
166
+
167
+ def t5(t):
168
+ _seeded(71)
169
+ values = _torch.tensor([
170
+ -64.0, -1.001, -1.0, -0.999, -0.5002442,
171
+ -0.3332519, 0.3332519, 0.5002442, 0.9989,
172
+ 0.999, 0.9991, 1.0, 1.001, 64.0,
173
+ ], dtype=_torch.float32)
174
+ return [values.repeat(19, 20)[:, :259]]
175
+
176
+ return _ew_suites() + [
177
+ ("T4_misaligned_upper_clamp_tail", 1, t4),
178
+ ("T5_clamp_and_fp16_neighborhoods", 1, t5),
179
+ ]
180
+
181
+
182
+ def _softsign_suites():
183
+ def t4(t):
184
+ _seeded(73)
185
+ x = _torch.full((3, 257), 1.0e-4, dtype=_torch.float32)
186
+ x[:, 0::2] = 4096.0
187
+ x[:, -1] = 32768.0
188
+ return [x]
189
+
190
+ def t5(t):
191
+ _seeded(79)
192
+ outputs = (_torch.arange(1, 256, dtype=_torch.float32) + 0.5) / 256.0
193
+ x = (outputs / (1.0 - outputs)).reshape(3, 85)
194
+ x[0, 0] = 65504.0
195
+ x[-1, -1] = 1.0e8
196
+ return [x]
197
+
198
+ return _ew_suites() + [
199
+ ("T4_misaligned_alternating_tail_spike", 1, t4),
200
+ ("T5_positive_fp16_rounding_lattice", 1, t5),
201
+ ]
202
+
203
+
204
+ def _selu_suites():
205
+ def t0(t):
206
+ _seeded(1000 + t)
207
+ return [_torch.rand(4096, 393216)]
208
+
209
+ def t1(t):
210
+ _seeded(7)
211
+ return [_torch.randn(4096, 393216)]
212
+
213
+ def t2(t):
214
+ _seeded(9)
215
+ return [_torch.randn(4096, 393216) * 100.0]
216
+
217
+ def t3(t):
218
+ _seeded(8)
219
+ return [_torch.randn(127, 4097)]
220
+
221
+ def t4(t):
222
+ _seeded(27)
223
+ values = _torch.tensor([
224
+ -8.0, -4.0, -2.0, -1.0, -0.5, -0.125,
225
+ -2.0e-6, -1.0e-6, -0.0, 0.0, 5.0e-7, 1.0e-6,
226
+ 1.5e-6, 2.0e-6, 0.125, 0.5, 1.0, 4.0,
227
+ ], dtype=_torch.float32)
228
+ return [values.repeat(17, 15)[:, :257]]
229
+
230
+ def t5(t):
231
+ _seeded(28)
232
+ x = _torch.full((31, 257), -0.5, dtype=_torch.float32)
233
+ x[:, 0::4] = -8.0
234
+ x[:, 1::4] = -2.0
235
+ x[:, 2::4] = -0.125
236
+ x[:, -1] = -1.0e-6
237
+ return [x]
238
+
239
+ def t6(t):
240
+ _seeded(29)
241
+ x = _torch.linspace(-9.0, -1.0e-4, 259, dtype=_torch.float32)
242
+ return [x.repeat(33, 1)]
243
+
244
+ return [("T0_original", 5, t0), ("T1_signed", 1, t1),
245
+ ("T2_large", 1, t2), ("T3_misaligned", 1, t3),
246
+ ("T4_branch_threshold_neighborhood", 1, t4),
247
+ ("T5_misaligned_negative_stripes", 1, t5),
248
+ ("T6_negative_exponential_sweep", 1, t6)]
249
+
250
+
251
+ def _elu_suites():
252
+ def t0(t):
253
+ _seeded(1000 + t)
254
+ return [_torch.rand(4096, 393216)]
255
+
256
+ def t1(t):
257
+ _seeded(7)
258
+ return [_torch.randn(4096, 393216)]
259
+
260
+ def t2(t):
261
+ _seeded(9)
262
+ return [_torch.randn(4096, 393216) * 100.0]
263
+
264
+ def t3(t):
265
+ _seeded(8)
266
+ return [_torch.randn(127, 4097)]
267
+
268
+ def t4(t):
269
+ _seeded(61)
270
+ values = _torch.tensor([
271
+ -1.0, -0.75, -0.5, -0.25, -0.125, -0.03125,
272
+ -1.0e-3, -1.0e-5, -0.0, 0.0, 1.0e-5, 1.0e-3,
273
+ 0.03125, 0.125, 0.25, 0.5, 0.75, 1.0,
274
+ ], dtype=_torch.float32)
275
+ return [values.repeat(17, 15)[:, :257]]
276
+
277
+ def t5(t):
278
+ _seeded(67)
279
+ values = _torch.tensor([
280
+ -0.015625, -0.03125, -0.0625, -0.125, -0.25,
281
+ -0.5, -1.0, -2.0, -4.0, -8.0, -16.0,
282
+ ], dtype=_torch.float32)
283
+ return [values.repeat(31, 24)[:, :259]]
284
+
285
+ def t6(t):
286
+ _seeded(71)
287
+ x = _torch.full((3, 257), -0.5, dtype=_torch.float32)
288
+ x[:, 0::4] = -8.0
289
+ x[:, 1::4] = 0.25
290
+ x[:, 2::4] = -0.03125
291
+ x[:, -1] = -16.0
292
+ return [x]
293
+
294
+ return [("T0_original", 5, t0), ("T1_signed", 1, t1),
295
+ ("T2_large", 1, t2), ("T3_misaligned", 1, t3),
296
+ ("T4_branch_threshold_sweep", 1, t4),
297
+ ("T5_negative_exponential_ladder", 1, t5),
298
+ ("T6_misaligned_alternating_tail", 1, t6)]
299
+
300
+
301
+ def _softplus_suites():
302
+ def t0(t):
303
+ _seeded(1000 + t)
304
+ return [_torch.rand(4096, 393216)]
305
+
306
+ def t1(t):
307
+ _seeded(7)
308
+ return [_torch.randn(4096, 393216)]
309
+
310
+ def t2(t):
311
+ _seeded(9)
312
+ return [_torch.randn(4096, 393216) * 100.0]
313
+
314
+ def t3(t):
315
+ _seeded(8)
316
+ return [_torch.randn(127, 4097)]
317
+
318
+ def t4(t):
319
+ _seeded(47)
320
+ values = _torch.tensor([
321
+ 7.999, 8.0, 8.001, 9.0, 12.0, 16.0,
322
+ 19.999, 20.0, 20.001,
323
+ ], dtype=_torch.float32)
324
+ return [values.repeat(29, 31)[:, :257]]
325
+
326
+ def t5(t):
327
+ _seeded(53)
328
+ x = _torch.full((31, 257), 8.0, dtype=_torch.float32)
329
+ x[:, 0::4] = 0.0
330
+ x[:, 1::4] = 7.999
331
+ x[:, 2::4] = 20.0
332
+ x[:, -1] = 20.001
333
+ return [x]
334
+
335
+ def t6(t):
336
+ _seeded(59)
337
+ values = _torch.tensor([
338
+ -20.0, -16.0, -12.0, -9.0, -8.0, -6.0,
339
+ -4.0, -2.0, -1.0, -0.5, 0.0, 0.5, 1.0, 2.0,
340
+ 4.0, 6.0, 7.5, 7.999,
341
+ ], dtype=_torch.float32)
342
+ return [values.repeat(37, 15)[:, :257]]
343
+
344
+ return [("T0_original", 5, t0), ("T1_signed", 1, t1),
345
+ ("T2_large", 1, t2), ("T3_misaligned", 1, t3),
346
+ ("T4_cutoff_neighborhood", 1, t4),
347
+ ("T5_misaligned_cutoff_stripes", 1, t5),
348
+ ("T6_exponential_regime_sweep", 1, t6)]
349
+
350
+
351
+ def _ew_probe(torch):
352
+ torch.manual_seed(0)
353
+ return [("p_aligned", [torch.rand(32, 256)]),
354
+ ("p_misaligned", [torch.randn(7, 257)])]
355
+
356
+
357
+ _F = _torch.nn.functional
358
+ _ACTIVATIONS = {
359
+ "tanh": dict(kb="22_Tanh.py", expr="tanhf(val)",
360
+ ref=lambda x: _torch.tanh(x), suites=_tanh_suites),
361
+ "swish": dict(kb="25_Swish.py",
362
+ expr="val * (1.0f / (1.0f + expf(-val)))",
363
+ ref=lambda x: x * _torch.sigmoid(x), suites=_swish_suites),
364
+ "selu": dict(kb="27_SELU_.py",
365
+ expr="1.0507009873554805f * (val > 0.0f ? val : "
366
+ "1.6732632423543772f * (expf(val) - 1.0f))",
367
+ ref=lambda x: _torch.selu(x), suites=_selu_suites),
368
+ "hardsigmoid": dict(kb="28_HardSigmoid.py",
369
+ expr="fminf(fmaxf(val / 6.0f + 0.5f, 0.0f), 1.0f)",
370
+ ref=lambda x: _F.hardsigmoid(x),
371
+ suites=_hardsigmoid_suites),
372
+ "softplus": dict(kb="29_Softplus.py",
373
+ expr="val > 20.0f ? val : log1pf(expf(val))",
374
+ ref=lambda x: _F.softplus(x), suites=_softplus_suites),
375
+ "softsign": dict(kb="30_Softsign.py",
376
+ expr="val / (1.0f + fabsf(val))",
377
+ ref=lambda x: _F.softsign(x), suites=_softsign_suites),
378
+ "elu": dict(kb="31_ELU.py",
379
+ expr="val > 0.0f ? val : (expf(val) - 1.0f)",
380
+ ref=lambda x: _F.elu(x), suites=_elu_suites),
381
+ "hardtanh": dict(kb="32_HardTanh.py",
382
+ expr="fminf(fmaxf(val, -1.0f), 1.0f)",
383
+ ref=lambda x: _F.hardtanh(x), suites=_hardtanh_suites),
384
+ }
385
+
386
+ # ----------------------------------------------------------- matmul variants
387
+
388
+ _MM_TMPL = r"""
389
+ #include <cuda_fp16.h>
390
+
391
+ #define TILE 32
392
+
393
+ __global__ void {kname}(const float* A, const float* B, float* C,
394
+ int M, int K, int N) {{
395
+ __shared__ float As[TILE][TILE];
396
+ __shared__ float Bs[TILE][TILE];
397
+ int row = blockIdx.y * TILE + threadIdx.y;
398
+ int col = blockIdx.x * TILE + threadIdx.x;
399
+ float acc = 0.0f;
400
+ int numTiles = (K + TILE - 1) / TILE;
401
+ for (int t = 0; t < numTiles; t++) {{
402
+ int a_k = t * TILE + threadIdx.x;
403
+ int b_k = t * TILE + threadIdx.y;
404
+ As[threadIdx.y][threadIdx.x] = {a_load};
405
+ Bs[threadIdx.y][threadIdx.x] = {b_load};
406
+ __syncthreads(); // sync-after-load
407
+ for (int k = 0; k < TILE; k++) {{
408
+ acc += As[threadIdx.y][k] * Bs[k][threadIdx.x];
409
+ }}
410
+ __syncthreads(); // sync-after-compute
411
+ }}
412
+ if (row < M && col < N) {{ C[(long long)row * N + col] = acc; }}
413
+ }}
414
+ """
415
+
416
+ _A_NORMAL = "(row < M && a_k < K) ? A[(long long)row * K + a_k] : 0.0f"
417
+ _A_TRANS = "(a_k < K && row < M) ? A[(long long)a_k * M + row] : 0.0f"
418
+ _B_NORMAL = "(b_k < K && col < N) ? B[(long long)b_k * N + col] : 0.0f"
419
+ _B_TRANS = "(b_k < K && col < N) ? B[(long long)col * K + b_k] : 0.0f"
420
+
421
+
422
+ def _mm_launch(a_layout, b_layout):
423
+ def launch(inputs, torch):
424
+ A, B = inputs
425
+ if a_layout == "t":
426
+ Kd, M = A.shape
427
+ else:
428
+ M, Kd = A.shape
429
+ N = B.shape[0] if b_layout == "t" else B.shape[1]
430
+ out = torch.zeros((M, N), device=A.device, dtype=A.dtype)
431
+ return out, ((N + 31) // 32, (M + 31) // 32, 1), (32, 32, 1), \
432
+ [(ctypes.c_int, M), (ctypes.c_int, Kd), (ctypes.c_int, N)]
433
+ return launch
434
+
435
+
436
+ def _mm_var_suites(m, k, n, a_layout, b_layout, symmetric=False):
437
+ def a_shape():
438
+ return (k, m) if a_layout == "t" else (m, k)
439
+
440
+ def b_shape():
441
+ return (n, k) if b_layout == "t" else (k, n)
442
+
443
+ def gen(fn):
444
+ A, B = fn(*a_shape()), fn(*b_shape())
445
+ if symmetric:
446
+ A = (A + A.T) / 2
447
+ B = (B + B.T) / 2
448
+ return [A, B]
449
+
450
+ def t0(t):
451
+ _seeded(1000 + t)
452
+ return gen(_torch.rand)
453
+
454
+ def t1(t):
455
+ _seeded(7)
456
+ return gen(_torch.randn)
457
+
458
+ def t2(t):
459
+ _seeded(9)
460
+ return gen(lambda *s: _torch.rand(*s) * 50.0)
461
+
462
+ def t3(t):
463
+ _seeded(11)
464
+ m3, k3, n3 = 515, 1027, 259
465
+ if symmetric:
466
+ m3 = k3 = n3 = 515
467
+ A = _torch.randn(*((k3, m3) if a_layout == "t" else (m3, k3)))
468
+ B = _torch.randn(*((n3, k3) if b_layout == "t" else (k3, n3)))
469
+ if symmetric:
470
+ A = (A + A.T) / 2
471
+ B = (B + B.T) / 2
472
+ return [A, B]
473
+
474
+ def t4(t):
475
+ _seeded(13)
476
+ A, B = gen(_torch.rand)
477
+ A += 0.0
478
+ if a_layout == "t":
479
+ A[-32:, :] = 100.0
480
+ else:
481
+ A[:, -32:] = 100.0
482
+ if b_layout == "t":
483
+ B[:, -32:] = 100.0
484
+ else:
485
+ B[-32:, :] = 100.0
486
+ return [A, B]
487
+
488
+ def t5(t):
489
+ _seeded(17)
490
+ m5, k5, n5 = 39, 33, 35
491
+ rows = _torch.arange(m5, dtype=_torch.float32)[:, None]
492
+ red = _torch.arange(k5, dtype=_torch.float32)[None, :]
493
+ cols = _torch.arange(n5, dtype=_torch.float32)[None, :]
494
+ A = 0.25 + rows * 0.125 + red * 0.03125
495
+ B = 0.5 + red.T * 0.0625 + cols * 0.015625
496
+ return [A, B]
497
+
498
+ def t6(t):
499
+ _seeded(19)
500
+ m6, k6, n6 = 35, 33, 39
501
+ rows = _torch.arange(m6, dtype=_torch.float32)[:, None]
502
+ red = _torch.arange(k6, dtype=_torch.float32)[None, :]
503
+ cols = _torch.arange(n6, dtype=_torch.float32)[None, :]
504
+ A = 0.125 + rows * 0.0625 + red * 0.015625
505
+ B = 0.375 + red.T * 0.03125 + cols * 0.125
506
+ return [A, B]
507
+
508
+ def t7(t):
509
+ _seeded(23)
510
+ m7, k7, n7 = 37, 33, 41
511
+ A = _torch.full((m7, k7), 1.0e-3)
512
+ B = _torch.full((k7, n7), 1.0e-3)
513
+ A[:, -1] = 32.0 + _torch.arange(m7, dtype=_torch.float32)
514
+ B[-1, :] = 48.0 + _torch.arange(n7, dtype=_torch.float32)
515
+ return [A, B]
516
+
517
+ def t8(t):
518
+ _seeded(29)
519
+ m8, k8, n8 = 1025, 8191, 1025
520
+ A = _torch.ones((m8, k8), dtype=_torch.float32)
521
+ B = _torch.ones((n8, k8), dtype=_torch.float32)
522
+ A[:, -1] = 64.0
523
+ B[:, -1] = 96.0
524
+ return [A, B]
525
+
526
+ def t9(t):
527
+ _seeded(31)
528
+ m9, k9, n9 = 33, 31, 35
529
+ rows = _torch.arange(m9, dtype=_torch.float32)[:, None]
530
+ cols = _torch.arange(n9, dtype=_torch.float32)[:, None]
531
+ A = 0.25 + rows * 0.03125 + _torch.arange(
532
+ k9, dtype=_torch.float32)[None, :] * 0.015625
533
+ B = 0.5 + cols * 0.0625 + _torch.arange(
534
+ k9, dtype=_torch.float32)[None, :] * 0.03125
535
+ A[:, -1] = 48.0 + rows[:, 0]
536
+ B[:, -1] = 64.0 + cols[:, 0]
537
+ return [A, B]
538
+
539
+ def t10(t):
540
+ _seeded(37)
541
+ m10, k10, n10 = 35, 31, 37
542
+ red = _torch.arange(k10, dtype=_torch.float32)[:, None]
543
+ rows = _torch.arange(m10, dtype=_torch.float32)[None, :]
544
+ cols = _torch.arange(n10, dtype=_torch.float32)[:, None]
545
+ A = 0.25 + red * 0.03125 + rows * 0.125
546
+ B = 0.5 + cols * 0.25 + red.T * 0.0625
547
+ return [A, B]
548
+
549
+ def t11(t):
550
+ _seeded(41)
551
+ m11, k11, n11 = 33, 30, 35
552
+ A = _torch.full((k11, m11), 1.0e-3)
553
+ B = _torch.full((n11, k11), 1.0e-3)
554
+ A[-1, :] = 64.0 + _torch.arange(m11, dtype=_torch.float32)
555
+ B[:, -1] = 96.0 + _torch.arange(n11, dtype=_torch.float32)
556
+ return [A, B]
557
+
558
+ def t12(t):
559
+ _seeded(43)
560
+ m12, k12, n12 = 47, 63, 45
561
+ red = _torch.arange(k12, dtype=_torch.float32)[:, None]
562
+ rows = _torch.arange(m12, dtype=_torch.float32)[None, :]
563
+ cols = _torch.arange(n12, dtype=_torch.float32)[:, None]
564
+ A = 0.125 + red.remainder(2) * 31.875 + rows * 0.0625
565
+ B = 0.25 + (cols + red.T).remainder(2) * 47.75
566
+ return [A, B]
567
+
568
+ return lambda: [("T0_original", 5, t0), ("T1_signed", 1, t1),
569
+ ("T2_large", 1, t2), ("T3_misaligned", 1, t3),
570
+ ("T4_last_tile_spike", 1, t4)] + (
571
+ [("T5_rect_m_gt_n_positional", 1, t5),
572
+ ("T6_rect_n_gt_m_positional", 1, t6),
573
+ ("T7_partial_tile_tail_mass", 1, t7)]
574
+ if symmetric else []) + (
575
+ [("T8_tb_wide_stride_guard_edges", 1, t8),
576
+ ("T9_tb_k31_positional_tail_spike", 1, t9)]
577
+ if (a_layout, b_layout, symmetric) == ("n", "t", False)
578
+ else []) + (
579
+ [("T10_tab_k31_positional_boundary", 1, t10),
580
+ ("T11_tab_k30_tail_mass", 1, t11),
581
+ ("T12_tab_k63_alternating", 1, t12)]
582
+ if (a_layout, b_layout, symmetric) == ("t", "t", False)
583
+ else [])
584
+
585
+
586
+ def _mm_probe(a_layout, b_layout, symmetric=False):
587
+ def probe(torch):
588
+ torch.manual_seed(0)
589
+ m, k, n = (64, 128, 96) if not symmetric else (64, 64, 64)
590
+ m2, k2, n2 = (67, 131, 53) if not symmetric else (67, 67, 67)
591
+ def mk(mm, kk, nn):
592
+ A = torch.randn(*((kk, mm) if a_layout == "t" else (mm, kk)))
593
+ B = torch.randn(*((nn, kk) if b_layout == "t" else (kk, nn)))
594
+ if symmetric:
595
+ A = (A + A.T) / 2
596
+ B = (B + B.T) / 2
597
+ return [A, B]
598
+ return [("p_aligned", mk(m, k, n)), ("p_misaligned", mk(m2, k2, n2))]
599
+ return probe
600
+
601
+
602
+ # ----------------------------------------------------------- min reduction
603
+
604
+ MIN_CUDA = r"""
605
+ #include <cuda_fp16.h>
606
+ #include <math_constants.h>
607
+
608
+ __global__ void min_dim1_kernel(const float* x, float* out, int B, int R, int C) {
609
+ int c = blockIdx.x * blockDim.x + threadIdx.x;
610
+ int b = blockIdx.y;
611
+ if (c >= C) return;
612
+ float best = CUDART_INF_F;
613
+ for (int r = 0; r < R; r++) {
614
+ best = fminf(best, x[(long long)b * R * C + (long long)r * C + c]);
615
+ }
616
+ out[(long long)b * C + c] = best;
617
+ }
618
+ """
619
+
620
+
621
+ def _red2d_launch(inputs, torch):
622
+ x = inputs[0]
623
+ B, R, C = x.shape
624
+ out = torch.zeros((B, C), device=x.device, dtype=x.dtype)
625
+ return out, ((C + 255) // 256, B, 1), (256, 1, 1), \
626
+ [(ctypes.c_int, B), (ctypes.c_int, R), (ctypes.c_int, C)]
627
+
628
+
629
+ def _red_suites():
630
+ def t0(t):
631
+ _seeded(1000 + t)
632
+ return [_torch.rand(128, 4096, 4095)]
633
+
634
+ def t1(t):
635
+ _seeded(7)
636
+ return [_torch.randn(128, 4096, 4095)]
637
+
638
+ def t4(t):
639
+ _seeded(13)
640
+ x = _torch.rand(128, 4096, 4095)
641
+ x[:, 0, :] -= 100.0
642
+ x[:, -1, :] -= 100.0
643
+ return [x]
644
+
645
+ def t5(t):
646
+ _seeded(17)
647
+ return [_torch.rand(128, 4096, 4095) + 1.0]
648
+
649
+ def t6(t):
650
+ _seeded(19)
651
+ x = _torch.full((17, 257, 259), 64.0, dtype=_torch.float32)
652
+ x[:, 0::2, :] = 7.0
653
+ x[:, 1::4, :] = 7.0
654
+ x[:, -1, :] = 7.0
655
+ return [x]
656
+
657
+ def t7(t):
658
+ _seeded(23)
659
+ x = _torch.full((19, 33, 257), 1.0, dtype=_torch.float32)
660
+ x[:, 0::4, :] = 0.0
661
+ x[:, 2::4, :] = -0.0
662
+ x[:, -2, :] = -0.0
663
+ x[:, -1, :] = 0.0
664
+ return [x]
665
+
666
+ return [("T0_original", 5, t0), ("T1_signed", 1, t1),
667
+ ("T4_edge_row_dip", 1, t4), ("T5_all_positive_shifted", 1, t5),
668
+ ("T6_duplicate_minima_ordered", 1, t6),
669
+ ("T7_signed_zero_ties", 1, t7)]
670
+
671
+
672
+ def _red_probe(torch):
673
+ torch.manual_seed(0)
674
+ return [("p_aligned", [torch.rand(4, 64, 256)]),
675
+ ("p_misaligned", [torch.randn(4, 64, 255)])]
676
+
677
+
678
+ # ------------------------------------------------------------ L1 / L2 norm
679
+
680
+ _NORM_TMPL = r"""
681
+ #include <cuda_fp16.h>
682
+
683
+ __global__ void {kname}(const float* x, float* out, int dim) {{
684
+ long long row = blockIdx.x;
685
+ const float* xr = x + row * dim;
686
+ float* outr = out + row * dim;
687
+ __shared__ float sdata[256];
688
+ int tid = threadIdx.x;
689
+ int iters = (dim + 255) / 256;
690
+ float local_sum = 0.0f;
691
+ for (int it = 0; it < iters; it++) {{
692
+ int i = it * 256 + tid;
693
+ if (i < dim) {{ local_sum += {term}; }}
694
+ }}
695
+ sdata[tid] = local_sum;
696
+ __syncthreads(); // sync-sum-store
697
+ for (int s = 128; s > 0; s >>= 1) {{ // sum-reduce
698
+ if (tid < s) {{ sdata[tid] = sdata[tid] + sdata[tid + s]; }}
699
+ __syncthreads();
700
+ }}
701
+ float denom = {denom};
702
+ __syncthreads(); // sync-sum-read
703
+ for (int it = 0; it < iters; it++) {{
704
+ int i = it * 256 + tid;
705
+ if (i < dim) {{ outr[i] = xr[i] / denom; }}
706
+ }}
707
+ }}
708
+ """
709
+
710
+
711
+ def _rownorm_launch(inputs, torch):
712
+ x = inputs[0]
713
+ out = torch.zeros_like(x)
714
+ return out, (x.shape[0], 1, 1), (256, 1, 1), [(ctypes.c_int, x.shape[1])]
715
+
716
+
717
+ def _rownorm_suites():
718
+ def t0(t):
719
+ _seeded(1000 + t)
720
+ return [_torch.rand(32768, 65535)]
721
+
722
+ def t1(t):
723
+ _seeded(7)
724
+ return [_torch.randn(32768, 65535)]
725
+
726
+ def t4(t):
727
+ _seeded(13)
728
+ x = _torch.randn(512, 65535) * 0.01
729
+ x[:, -1] = 1000.0
730
+ return [x]
731
+
732
+ return [("T0_original", 5, t0), ("T1_signed", 1, t1),
733
+ ("T4_tail_spike", 1, t4)]
734
+
735
+
736
+ def _rownorm_probe(torch):
737
+ torch.manual_seed(0)
738
+ return [("p_aligned", [torch.rand(4, 512)]),
739
+ ("p_misaligned", [torch.randn(3, 259)])]
740
+
741
+
742
+ # ------------------------------------------------------------------- register
743
+
744
+ def _register():
745
+ for name, spec in _ACTIVATIONS.items():
746
+ K.PROBLEMS[name] = dict(
747
+ kb_file=spec["kb"],
748
+ cuda=_EW_TMPL.format(kname=f"{name}_kernel", expr=spec["expr"]),
749
+ kernel_name=f"{name}_kernel", ref=spec["ref"],
750
+ launch=_ew_launch, suites=spec.get("suites", _ew_suites),
751
+ probe=_ew_probe)
752
+
753
+ mm_variants = {
754
+ "matmul_tb": dict(kb="17_Matmul_with_transposed_B.py",
755
+ a="n", b="t", sym=False, m=2048, k=8192, n=4096,
756
+ ref=lambda A, B: _torch.matmul(A, B.T)),
757
+ "matmul_tab": dict(kb="18_Matmul_with_transposed_both.py",
758
+ a="t", b="t", sym=False, m=2048, k=8192, n=4096,
759
+ ref=lambda A, B: _torch.matmul(A.T, B.T)),
760
+ "matmul_sym": dict(kb="13_Matmul_for_symmetric_matrices.py",
761
+ a="n", b="n", sym=True, m=4096, k=4096, n=4096,
762
+ ref=lambda A, B: _torch.matmul(A, B)),
763
+ }
764
+ for name, v in mm_variants.items():
765
+ a_load = _A_TRANS if v["a"] == "t" else _A_NORMAL
766
+ b_load = _B_TRANS if v["b"] == "t" else _B_NORMAL
767
+ K.PROBLEMS[name] = dict(
768
+ kb_file=v["kb"],
769
+ cuda=_MM_TMPL.format(kname=f"{name}_kernel",
770
+ a_load=a_load, b_load=b_load),
771
+ kernel_name=f"{name}_kernel", ref=v["ref"],
772
+ launch=_mm_launch(v["a"], v["b"]),
773
+ suites=_mm_var_suites(v["m"], v["k"], v["n"], v["a"], v["b"], v["sym"]),
774
+ probe=_mm_probe(v["a"], v["b"], v["sym"]))
775
+
776
+ K.PROBLEMS["min"] = dict(
777
+ kb_file="53_Min_reduction_over_a_dimension.py", cuda=MIN_CUDA,
778
+ kernel_name="min_dim1_kernel",
779
+ ref=lambda x: _torch.min(x, dim=1)[0],
780
+ launch=_red2d_launch, suites=_red_suites, probe=_red_probe)
781
+
782
+ K.PROBLEMS["l1norm"] = dict(
783
+ kb_file="38_L1Norm_.py",
784
+ cuda=_NORM_TMPL.format(kname="l1norm_kernel",
785
+ term="fabsf(xr[i])", denom="sdata[0] / dim"),
786
+ kernel_name="l1norm_kernel",
787
+ ref=lambda x: x / _torch.mean(_torch.abs(x), dim=1, keepdim=True),
788
+ launch=_rownorm_launch, suites=_rownorm_suites, probe=_rownorm_probe)
789
+
790
+ K.PROBLEMS["l2norm"] = dict(
791
+ kb_file="39_L2Norm_.py",
792
+ cuda=_NORM_TMPL.format(kname="l2norm_kernel",
793
+ term="xr[i] * xr[i]", denom="sqrtf(sdata[0])"),
794
+ kernel_name="l2norm_kernel",
795
+ ref=lambda x: x / _torch.norm(x, p=2, dim=1, keepdim=True),
796
+ launch=_rownorm_launch, suites=_rownorm_suites, probe=_rownorm_probe)
797
+
798
+
799
+ _register()
pipeline/problems_ext.py ADDED
@@ -0,0 +1,672 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Extended problem registry: 9 more KernelBench level1 problems.
2
+
3
+ Each entry is registry-driven (no per-problem code in screen_mutants):
4
+ cuda device-only CUDA source (mutation substrate)
5
+ kernel_name __global__ symbol
6
+ ref torch reference callable (must match the KB Model semantics)
7
+ launch (inputs, torch) -> (out, grid, block, scalar ctypes args)
8
+ suites () -> [(name, n_trials, builder)]
9
+ probe (torch) -> [(name, [cpu tensors])] tiny crash-quarantine inputs
10
+
11
+ Import side effect: registers everything into kernels_def.PROBLEMS.
12
+ """
13
+ import ctypes
14
+
15
+ import torch as _torch # only for type hints in refs; runtime torch passed in
16
+
17
+ import kernels_def as K
18
+
19
+
20
+ def _seeded(seed):
21
+ _torch.manual_seed(seed)
22
+
23
+
24
+ # --------------------------------------------------------------- elementwise
25
+
26
+ def _ew_launch(inputs, torch):
27
+ x = inputs[0]
28
+ out = torch.zeros_like(x)
29
+ n = x.numel()
30
+ return out, ((n + 255) // 256, 1, 1), (256, 1, 1), [(ctypes.c_longlong, n)]
31
+
32
+
33
+ def _ew_suites():
34
+ def t0(t):
35
+ _seeded(1000 + t)
36
+ return [_torch.rand(4096, 393216)]
37
+
38
+ def t1(t):
39
+ _seeded(7)
40
+ return [_torch.randn(4096, 393216)]
41
+
42
+ def t2(t):
43
+ _seeded(9)
44
+ return [_torch.randn(4096, 393216) * 100.0]
45
+
46
+ def t3(t):
47
+ _seeded(8)
48
+ return [_torch.randn(127, 4097)]
49
+
50
+ return [("T0_original", 5, t0), ("T1_signed", 1, t1),
51
+ ("T2_large", 1, t2), ("T3_misaligned", 1, t3)]
52
+
53
+
54
+ def _leakyrelu_suites():
55
+ suites = _ew_suites()
56
+
57
+ def t4(t):
58
+ _seeded(26043)
59
+ x = _torch.full((31, 257), 1e-4)
60
+ x[:, -1] = 1e3
61
+ x.reshape(-1)[::256] = 2e3
62
+ return [x]
63
+
64
+ def t5(t):
65
+ _seeded(26044)
66
+ transition = _torch.tensor([
67
+ -2e-6, -1e-6, -5e-7, -1e-7, 0.0,
68
+ 1e-7, 5e-7, 1e-6, 2e-6,
69
+ ])
70
+ return [transition.repeat(29, 29)[:, :257].contiguous()]
71
+
72
+ suites.extend([
73
+ ("T4_misaligned_tail_spikes", 1, t4),
74
+ ("T5_threshold_transition_grid", 1, t5),
75
+ ])
76
+ return suites
77
+
78
+
79
+ def _gelu_suites():
80
+ suites = _ew_suites()
81
+
82
+ def t4(t):
83
+ _seeded(26041)
84
+ x = _torch.full((127, 4097), 70000.0)
85
+ x[:, -1] = 65520.0
86
+ return [x]
87
+
88
+ def t5(t):
89
+ _seeded(26042)
90
+ transition = _torch.tensor([
91
+ -4.0, -3.0, -2.5, -2.0, -1.5, -1.0, -0.5,
92
+ 0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0,
93
+ ])
94
+ return [transition.repeat(17, 18)[:, :257].contiguous()]
95
+
96
+ suites.extend([
97
+ ("T4_misaligned_fp16_overflow", 1, t4),
98
+ ("T5_erf_transition_grid", 1, t5),
99
+ ])
100
+ return suites
101
+
102
+
103
+ def _sigmoid_suites():
104
+ suites = _ew_suites()
105
+
106
+ def t4(t):
107
+ _seeded(26043)
108
+ x = _torch.full((255, 257), 12.0)
109
+ x[:, ::2] = -12.0
110
+ x.reshape(-1)[-1] = 0.0
111
+ return [x]
112
+
113
+ def t5(t):
114
+ _seeded(26044)
115
+ transition = _torch.tensor([
116
+ -6.0, -4.0, -2.0, -1.0, -0.5, -0.125,
117
+ 0.0, 0.125, 0.5, 1.0, 2.0, 4.0, 6.0,
118
+ ])
119
+ return [transition.repeat(129, 20)[:, :257].contiguous()]
120
+
121
+ suites.extend([
122
+ ("T4_misaligned_alternating_tail", 1, t4),
123
+ ("T5_fp16_transition_grid", 1, t5),
124
+ ])
125
+ return suites
126
+
127
+
128
+ def _ew_probe(torch):
129
+ torch.manual_seed(0)
130
+ return [("p_aligned", [torch.rand(32, 256)]),
131
+ ("p_misaligned", [torch.randn(7, 257)])]
132
+
133
+
134
+ _EW_TMPL = r"""
135
+ #include <cuda_fp16.h>
136
+
137
+ __global__ void {kname}(const float* x, float* out, long long n) {{
138
+ long long idx = (long long)blockIdx.x * blockDim.x + threadIdx.x;
139
+ if (idx < n) {{ float val = x[idx]; out[idx] = {expr}; }}
140
+ }}
141
+ """
142
+
143
+ _ELEMENTWISE = {
144
+ "leakyrelu": dict(
145
+ kb="20_LeakyReLU.py",
146
+ expr="val > 0.0f ? val : 0.01f * val",
147
+ ref=lambda x: _torch.nn.functional.leaky_relu(x, 0.01),
148
+ suites=_leakyrelu_suites),
149
+ "gelu": dict(
150
+ kb="26_GELU_.py",
151
+ expr="0.5f * val * (1.0f + erff(val * 0.70710678f))",
152
+ ref=lambda x: _torch.nn.functional.gelu(x), suites=_gelu_suites),
153
+ "sigmoid": dict(
154
+ kb="21_Sigmoid.py",
155
+ expr="1.0f / (1.0f + expf(-val))",
156
+ ref=lambda x: _torch.sigmoid(x), suites=_sigmoid_suites),
157
+ }
158
+
159
+ # --------------------------------------------------------------- logsoftmax
160
+
161
+ LOGSOFTMAX_CUDA = r"""
162
+ #include <cuda_fp16.h>
163
+ #include <math_constants.h>
164
+
165
+ __global__ void logsoftmax_kernel(const float* x, float* out, int dim) {
166
+ long long row = blockIdx.x;
167
+ const float* xr = x + row * dim;
168
+ float* outr = out + row * dim;
169
+ __shared__ float sdata[256];
170
+ int tid = threadIdx.x;
171
+ int iters = (dim + 255) / 256;
172
+
173
+ float local_max = -CUDART_INF_F;
174
+ for (int it = 0; it < iters; it++) {
175
+ int i = it * 256 + tid;
176
+ if (i < dim) { local_max = fmaxf(local_max, xr[i]); }
177
+ }
178
+ sdata[tid] = local_max;
179
+ __syncthreads(); // sync-max-store
180
+ for (int s = 128; s > 0; s >>= 1) { // max-reduce
181
+ if (tid < s) { sdata[tid] = fmaxf(sdata[tid], sdata[tid + s]); }
182
+ __syncthreads();
183
+ }
184
+ float row_max = sdata[0];
185
+ __syncthreads(); // sync-max-read
186
+
187
+ float local_sum = 0.0f;
188
+ for (int it = 0; it < iters; it++) {
189
+ int i = it * 256 + tid;
190
+ if (i < dim) { local_sum += expf(xr[i] - row_max); }
191
+ }
192
+ sdata[tid] = local_sum;
193
+ __syncthreads(); // sync-sum-store
194
+ for (int s = 128; s > 0; s >>= 1) { // sum-reduce
195
+ if (tid < s) { sdata[tid] = sdata[tid] + sdata[tid + s]; }
196
+ __syncthreads();
197
+ }
198
+ float log_sum = logf(sdata[0]);
199
+ __syncthreads(); // sync-sum-read
200
+
201
+ for (int it = 0; it < iters; it++) {
202
+ int i = it * 256 + tid;
203
+ if (i < dim) { outr[i] = xr[i] - row_max - log_sum; }
204
+ }
205
+ }
206
+ """
207
+
208
+
209
+ def _lsm_launch(inputs, torch):
210
+ x = inputs[0]
211
+ out = torch.zeros_like(x)
212
+ return out, (x.shape[0], 1, 1), (256, 1, 1), [(ctypes.c_int, x.shape[1])]
213
+
214
+
215
+ def _lsm_suites():
216
+ def t0(t):
217
+ _seeded(1000 + t)
218
+ return [_torch.rand(4096, 393216)]
219
+
220
+ def t2(t):
221
+ _seeded(9)
222
+ return [_torch.randn(4096, 393216) * 100.0]
223
+
224
+ def t3(t):
225
+ _seeded(11)
226
+ x = _torch.zeros(4096, 393216)
227
+ cols = _torch.randint(0, 393216, (4096,))
228
+ x[_torch.arange(4096), cols] = 20.0
229
+ return [x]
230
+
231
+ def t4(t):
232
+ _seeded(13)
233
+ x = _torch.randn(64, 4099) * 0.01
234
+ x[:, -1] = 20.0
235
+ return [x]
236
+
237
+ def t5(t):
238
+ _seeded(17)
239
+ x = _torch.ones(64, 513)
240
+ x[:, 0] = 3000.0
241
+ return [x]
242
+
243
+ def t6(t):
244
+ _seeded(19)
245
+ x = _torch.ones(64, 4097)
246
+ x[:, 1::2] = 3000.0
247
+ x[:, -1] = 6000.0
248
+ return [x]
249
+
250
+ def t7(t):
251
+ _seeded(23)
252
+ x = _torch.ones(64, 259)
253
+ x[:, 258] = 70000.0
254
+ return [x]
255
+
256
+ return [("T0_original", 5, t0), ("T2_large", 1, t2),
257
+ ("T3_spiky", 1, t3), ("T4_tail_spike_misaligned", 1, t4),
258
+ ("T5_first_iteration_mass", 1, t5),
259
+ ("T6_alternating_lane_magnitude", 1, t6),
260
+ ("T7_fp16_overflow_misaligned", 1, t7)]
261
+
262
+
263
+ def _lsm_probe(torch):
264
+ torch.manual_seed(0)
265
+ x = torch.randn(16, 259) * 0.01
266
+ x[:, -1] = 20.0
267
+ return [("p_aligned", [torch.rand(16, 512)]),
268
+ ("p_large", [torch.randn(16, 512) * 100.0]),
269
+ ("p_misaligned_spike", [x])]
270
+
271
+
272
+ # --------------------------------------------------------------- matmul MK/TA
273
+
274
+ MATMUL_MK_CUDA = r"""
275
+ #include <cuda_fp16.h>
276
+
277
+ #define TILE 32
278
+
279
+ __global__ void matmul_mk_kernel(const float* A, const float* B, float* C,
280
+ int M, int K, int N) {
281
+ __shared__ float As[TILE][TILE];
282
+ __shared__ float Bs[TILE][TILE];
283
+ int row = blockIdx.y * TILE + threadIdx.y;
284
+ int col = blockIdx.x * TILE + threadIdx.x;
285
+ float acc = 0.0f;
286
+ int numTiles = (K + TILE - 1) / TILE;
287
+ for (int t = 0; t < numTiles; t++) {
288
+ int a_col = t * TILE + threadIdx.x;
289
+ int b_row = t * TILE + threadIdx.y;
290
+ As[threadIdx.y][threadIdx.x] = (row < M && a_col < K) ? A[(long long)row * K + a_col] : 0.0f;
291
+ Bs[threadIdx.y][threadIdx.x] = (b_row < K && col < N) ? B[(long long)b_row * N + col] : 0.0f;
292
+ __syncthreads(); // sync-after-load
293
+ for (int k = 0; k < TILE; k++) {
294
+ acc += As[threadIdx.y][k] * Bs[k][threadIdx.x];
295
+ }
296
+ __syncthreads(); // sync-after-compute
297
+ }
298
+ if (row < M && col < N) { C[(long long)row * N + col] = acc; }
299
+ }
300
+ """
301
+
302
+ MATMUL_TA_CUDA = r"""
303
+ #include <cuda_fp16.h>
304
+
305
+ #define TILE 32
306
+
307
+ __global__ void matmul_ta_kernel(const float* A, const float* B, float* C,
308
+ int M, int K, int N) {
309
+ __shared__ float As[TILE][TILE];
310
+ __shared__ float Bs[TILE][TILE];
311
+ int row = blockIdx.y * TILE + threadIdx.y;
312
+ int col = blockIdx.x * TILE + threadIdx.x;
313
+ float acc = 0.0f;
314
+ int numTiles = (K + TILE - 1) / TILE;
315
+ for (int t = 0; t < numTiles; t++) {
316
+ int a_k = t * TILE + threadIdx.x;
317
+ int b_k = t * TILE + threadIdx.y;
318
+ As[threadIdx.y][threadIdx.x] = (a_k < K && row < M) ? A[(long long)a_k * M + row] : 0.0f;
319
+ Bs[threadIdx.y][threadIdx.x] = (b_k < K && col < N) ? B[(long long)b_k * N + col] : 0.0f;
320
+ __syncthreads(); // sync-after-load
321
+ for (int k = 0; k < TILE; k++) {
322
+ acc += As[threadIdx.y][k] * Bs[k][threadIdx.x];
323
+ }
324
+ __syncthreads(); // sync-after-compute
325
+ }
326
+ if (row < M && col < N) { C[(long long)row * N + col] = acc; }
327
+ }
328
+ """
329
+
330
+
331
+ def _mm_launch_mk(inputs, torch):
332
+ A, B = inputs
333
+ M, Kd = A.shape
334
+ N = B.shape[1]
335
+ out = torch.zeros((M, N), device=A.device, dtype=A.dtype)
336
+ return out, ((N + 31) // 32, (M + 31) // 32, 1), (32, 32, 1), \
337
+ [(ctypes.c_int, M), (ctypes.c_int, Kd), (ctypes.c_int, N)]
338
+
339
+
340
+ def _mm_launch_ta(inputs, torch):
341
+ A, B = inputs
342
+ Kd, M = A.shape
343
+ N = B.shape[1]
344
+ out = torch.zeros((M, N), device=A.device, dtype=A.dtype)
345
+ return out, ((N + 31) // 32, (M + 31) // 32, 1), (32, 32, 1), \
346
+ [(ctypes.c_int, M), (ctypes.c_int, Kd), (ctypes.c_int, N)]
347
+
348
+
349
+ def _mm_suites(shapes):
350
+ (m, k, n), (m3, k3, n3), transposed = shapes
351
+
352
+ def a_shape(M, Kd):
353
+ return (Kd, M) if transposed else (M, Kd)
354
+
355
+ def t0(t):
356
+ _seeded(1000 + t)
357
+ return [_torch.rand(*a_shape(m, k)), _torch.rand(k, n)]
358
+
359
+ def t1(t):
360
+ _seeded(7)
361
+ return [_torch.randn(*a_shape(m, k)), _torch.randn(k, n)]
362
+
363
+ def t2(t):
364
+ # positive-only large values: kills fp16/precision mutants via overflow
365
+ # without triggering legitimate fp32 accumulation-order variance
366
+ # (signed large values false-kill correct kernels at K=8192, see sum/T2)
367
+ _seeded(9)
368
+ return [_torch.rand(*a_shape(m, k)) * 50.0, _torch.rand(k, n) * 50.0]
369
+
370
+ def t3(t):
371
+ _seeded(11)
372
+ return [_torch.randn(*a_shape(m3, k3)), _torch.randn(k3, n3)]
373
+
374
+ def t4(t):
375
+ _seeded(13)
376
+ A = _torch.rand(*a_shape(m, k))
377
+ B = _torch.rand(k, n)
378
+ if transposed:
379
+ A[-32:, :] = 100.0
380
+ else:
381
+ A[:, -32:] = 100.0
382
+ B[-32:, :] = 100.0
383
+ return [A, B]
384
+
385
+ suites = [("T0_original", 5, t0), ("T1_signed", 1, t1), ("T2_large", 1, t2),
386
+ ("T3_misaligned", 1, t3), ("T4_last_tile_spike", 1, t4)]
387
+ if not transposed:
388
+ return suites
389
+
390
+ def t5(t):
391
+ # Every logical dimension ends one lane before a tile boundary. The
392
+ # positive ramps make accidental boundary reads distinct and visible.
393
+ _seeded(101)
394
+ M, Kd, N = 1023, 31, 1023
395
+ A = (_torch.arange(Kd)[:, None] + 1.0) * 0.25
396
+ A = A.expand(Kd, M).clone()
397
+ A += (_torch.arange(M)[None, :] % 17) * 0.01
398
+ B = (_torch.arange(Kd)[:, None] + 1.0) * 0.125
399
+ B = B.expand(Kd, N).clone()
400
+ B += (_torch.arange(N)[None, :] % 19) * 0.01
401
+ return [A, B]
402
+
403
+ def t6(t):
404
+ # A one-element K tail puts the padding guard immediately beside a
405
+ # dominant, same-sign term while M and N also have partial blocks.
406
+ _seeded(103)
407
+ M, Kd, N = 95, 65, 93
408
+ A = _torch.full((Kd, M), 1.0e-3)
409
+ B = _torch.full((Kd, N), 1.0e-3)
410
+ A[-1, :] = 200.0 + (_torch.arange(M) % 11) * 0.25
411
+ B[-1, :] = 150.0 + (_torch.arange(N) % 13) * 0.25
412
+ return [A, B]
413
+
414
+ def t7(t):
415
+ # K == TILE - 1 directly exercises the mutated TILE - 1 tile-count
416
+ # expression; alternating positive magnitudes expose stray reads.
417
+ _seeded(107)
418
+ M, Kd, N = 63, 31, 61
419
+ scale = _torch.where(_torch.arange(Kd) % 2 == 0, 1.0e-3, 100.0)
420
+ A = scale[:, None].expand(Kd, M).clone()
421
+ B = scale[:, None].expand(Kd, N).clone()
422
+ A += (_torch.arange(M)[None, :] % 7) * 0.01
423
+ B += (_torch.arange(N)[None, :] % 5) * 0.01
424
+ return [A, B]
425
+
426
+ suites.extend([("T5_boundary_positional_ramps", 1, t5),
427
+ ("T6_single_tail_mass_spike", 1, t6),
428
+ ("T7_tile_minus1_alternating", 1, t7)])
429
+ return suites
430
+
431
+
432
+ def _mm_probe(transposed):
433
+ def probe(torch):
434
+ torch.manual_seed(0)
435
+ def a_shape(M, Kd):
436
+ return (Kd, M) if transposed else (M, Kd)
437
+ return [("p_aligned", [torch.rand(*a_shape(64, 128)), torch.rand(128, 96)]),
438
+ ("p_misaligned", [torch.randn(*a_shape(67, 131)), torch.randn(131, 53)])]
439
+ return probe
440
+
441
+
442
+ # --------------------------------------------------------- mean / max over dim1
443
+
444
+ MEAN_CUDA = r"""
445
+ #include <cuda_fp16.h>
446
+
447
+ __global__ void mean_dim1_kernel(const float* x, float* out, int B, int R, int C) {
448
+ int c = blockIdx.x * blockDim.x + threadIdx.x;
449
+ int b = blockIdx.y;
450
+ if (c >= C) return;
451
+ float acc = 0.0f;
452
+ for (int r = 0; r < R; r++) {
453
+ acc += x[(long long)b * R * C + (long long)r * C + c];
454
+ }
455
+ out[(long long)b * C + c] = acc / R;
456
+ }
457
+ """
458
+
459
+ MAX_CUDA = r"""
460
+ #include <cuda_fp16.h>
461
+ #include <math_constants.h>
462
+
463
+ __global__ void max_dim1_kernel(const float* x, float* out, int B, int R, int C) {
464
+ int c = blockIdx.x * blockDim.x + threadIdx.x;
465
+ int b = blockIdx.y;
466
+ if (c >= C) return;
467
+ float best = -CUDART_INF_F;
468
+ for (int r = 0; r < R; r++) {
469
+ best = fmaxf(best, x[(long long)b * R * C + (long long)r * C + c]);
470
+ }
471
+ out[(long long)b * C + c] = best;
472
+ }
473
+ """
474
+
475
+
476
+ def _red2d_launch(inputs, torch):
477
+ x = inputs[0]
478
+ B, R, C = x.shape
479
+ out = torch.zeros((B, C), device=x.device, dtype=x.dtype)
480
+ return out, ((C + 255) // 256, B, 1), (256, 1, 1), \
481
+ [(ctypes.c_int, B), (ctypes.c_int, R), (ctypes.c_int, C)]
482
+
483
+
484
+ def _red_suites(extra_negative):
485
+ def t0(t):
486
+ _seeded(1000 + t)
487
+ return [_torch.rand(128, 4096, 4095)]
488
+
489
+ def t1(t):
490
+ _seeded(7)
491
+ return [_torch.randn(128, 4096, 4095)]
492
+
493
+ def t4(t):
494
+ _seeded(13)
495
+ x = _torch.rand(128, 4096, 4095)
496
+ x[:, 0, :] += 100.0
497
+ x[:, -1, :] += 100.0
498
+ return [x]
499
+
500
+ suites = [("T0_original", 5, t0), ("T1_signed", 1, t1),
501
+ ("T4_edge_row_spike", 1, t4)]
502
+ if extra_negative:
503
+ def t5(t):
504
+ _seeded(17)
505
+ return [-_torch.rand(128, 4096, 4095) - 1.0]
506
+ suites.append(("T5_all_negative", 1, t5))
507
+
508
+ def t6(t):
509
+ _seeded(26045)
510
+ x = _torch.full((17, 257, 259), 32.0)
511
+ x[:, ::2, :] = 2048.0
512
+ x[:, 1::2, :] = 2048.0
513
+ return [x]
514
+
515
+ def t7(t):
516
+ _seeded(26046)
517
+ x = _torch.full((19, 129, 263), -64.0)
518
+ x[:, 0, :] = 1536.0
519
+ x[:, 64, :] = 1536.0
520
+ x[:, -1, :] = 1536.0
521
+ return [x]
522
+
523
+ def t8(t):
524
+ _seeded(26047)
525
+ x = _torch.full((23, 65, 257), -0.0)
526
+ x[:, 1::2, :] = 0.0
527
+ return [x]
528
+
529
+ suites.extend([
530
+ ("T6_alternating_duplicate_maxima", 1, t6),
531
+ ("T7_first_middle_last_ties", 1, t7),
532
+ ("T8_signed_zero_tie_order", 1, t8),
533
+ ])
534
+ return suites
535
+
536
+
537
+ def _red_probe(torch):
538
+ torch.manual_seed(0)
539
+ return [("p_aligned", [torch.rand(4, 64, 256)]),
540
+ ("p_misaligned", [torch.randn(4, 64, 255)])]
541
+
542
+
543
+ # --------------------------------------------------------------------- rmsnorm
544
+
545
+ RMSNORM_CUDA = r"""
546
+ #include <cuda_fp16.h>
547
+
548
+ __global__ void rmsnorm_kernel(const float* x, float* out, int B, int F, int S) {
549
+ int s = blockIdx.x * blockDim.x + threadIdx.x;
550
+ int b = blockIdx.y;
551
+ if (s >= S) return;
552
+ float sq = 0.0f;
553
+ for (int f = 0; f < F; f++) {
554
+ float v = x[(long long)b * F * S + (long long)f * S + s];
555
+ sq += v * v;
556
+ }
557
+ float rms = sqrtf(sq / F + 1e-5f);
558
+ for (int f = 0; f < F; f++) {
559
+ long long i = (long long)b * F * S + (long long)f * S + s;
560
+ out[i] = x[i] / rms;
561
+ }
562
+ }
563
+ """
564
+
565
+
566
+ def _rms_launch(inputs, torch):
567
+ x = inputs[0]
568
+ B, F, D1, D2 = x.shape
569
+ S = D1 * D2
570
+ out = torch.zeros_like(x)
571
+ return out, ((S + 255) // 256, B, 1), (256, 1, 1), \
572
+ [(ctypes.c_int, B), (ctypes.c_int, F), (ctypes.c_int, S)]
573
+
574
+
575
+ def _rms_ref(x):
576
+ rms = _torch.sqrt(_torch.mean(x ** 2, dim=1, keepdim=True) + 1e-5)
577
+ return x / rms
578
+
579
+
580
+ def _rms_suites():
581
+ def t0(t):
582
+ _seeded(1000 + t)
583
+ return [_torch.rand(112, 64, 512, 512)]
584
+
585
+ def t1(t):
586
+ _seeded(7)
587
+ return [_torch.randn(112, 64, 512, 512)]
588
+
589
+ def t3(t):
590
+ _seeded(11)
591
+ return [_torch.randn(7, 13, 33, 65)]
592
+
593
+ def t4(t):
594
+ _seeded(13)
595
+ x = _torch.rand(112, 64, 512, 512)
596
+ x[:, 0, :, :] += 50.0
597
+ x[:, -1, :, :] += 50.0
598
+ return [x]
599
+
600
+ return [("T0_original", 5, t0), ("T1_signed", 1, t1),
601
+ ("T3_misaligned", 1, t3), ("T4_feature_spike", 1, t4)]
602
+
603
+
604
+ def _rms_probe(torch):
605
+ torch.manual_seed(0)
606
+ return [("p_aligned", [torch.rand(2, 8, 16, 16)]),
607
+ ("p_misaligned", [torch.randn(3, 7, 13, 15)])]
608
+
609
+
610
+ # ------------------------------------------------------------------- register
611
+
612
+ def _register():
613
+ for name, spec in _ELEMENTWISE.items():
614
+ K.PROBLEMS[name] = dict(
615
+ kb_file=spec["kb"],
616
+ cuda=_EW_TMPL.format(kname=f"{name}_kernel", expr=spec["expr"]),
617
+ kernel_name=f"{name}_kernel", ref=spec["ref"],
618
+ launch=_ew_launch, suites=spec.get("suites", _ew_suites), probe=_ew_probe)
619
+
620
+ K.PROBLEMS["logsoftmax"] = dict(
621
+ kb_file="24_LogSoftmax.py", cuda=LOGSOFTMAX_CUDA,
622
+ kernel_name="logsoftmax_kernel",
623
+ ref=lambda x: _torch.log_softmax(x, dim=1),
624
+ launch=_lsm_launch, suites=_lsm_suites, probe=_lsm_probe)
625
+
626
+ K.PROBLEMS["matmul_mk"] = dict(
627
+ kb_file="2_Standard_matrix_multiplication_.py", cuda=MATMUL_MK_CUDA,
628
+ kernel_name="matmul_mk_kernel",
629
+ ref=lambda A, B: _torch.matmul(A, B),
630
+ launch=_mm_launch_mk,
631
+ suites=lambda: _mm_suites(((2048, 8192, 4096), (515, 1027, 259), False)),
632
+ probe=_mm_probe(False))
633
+
634
+ K.PROBLEMS["matmul_ta"] = dict(
635
+ kb_file="16_Matmul_with_transposed_A.py", cuda=MATMUL_TA_CUDA,
636
+ kernel_name="matmul_ta_kernel",
637
+ ref=lambda A, B: _torch.matmul(A.T, B),
638
+ launch=_mm_launch_ta,
639
+ suites=lambda: _mm_suites(((2048, 8192, 4096), (515, 1027, 259), True)),
640
+ probe=_mm_probe(True))
641
+
642
+ K.PROBLEMS["mean"] = dict(
643
+ kb_file="48_Mean_reduction_over_a_dimension.py", cuda=MEAN_CUDA,
644
+ kernel_name="mean_dim1_kernel",
645
+ ref=lambda x: _torch.mean(x, dim=1),
646
+ launch=_red2d_launch, suites=lambda: _red_suites(False), probe=_red_probe)
647
+
648
+ K.PROBLEMS["max"] = dict(
649
+ kb_file="49_Max_reduction_over_a_dimension.py", cuda=MAX_CUDA,
650
+ kernel_name="max_dim1_kernel",
651
+ ref=lambda x: _torch.max(x, dim=1)[0],
652
+ launch=_red2d_launch, suites=lambda: _red_suites(True), probe=_red_probe)
653
+
654
+ K.PROBLEMS["rmsnorm"] = dict(
655
+ kb_file="36_RMSNorm_.py", cuda=RMSNORM_CUDA,
656
+ kernel_name="rmsnorm_kernel", ref=_rms_ref,
657
+ launch=_rms_launch, suites=_rms_suites, probe=_rms_probe)
658
+
659
+
660
+ _register()
661
+
662
+ try:
663
+ import problems_batch2 # noqa: F401 (registers batch-2 substrates)
664
+ except ImportError:
665
+ pass
666
+
667
+ try:
668
+ import candidates_loader as _cl
669
+ _cl.load_accepted()
670
+ except Exception as _e:
671
+ import sys as _sys
672
+ print(f"[candidates] loader itself failed: {_e}", file=_sys.stderr, flush=True)
pipeline/recheck_nowitness.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Re-test no-witness mutants against the newly written killer suites.
2
+
3
+ Screening recorded each mutant's class once; mutants classed `no_witness`
4
+ survived every suite that existed AT THAT TIME. The witness hunt has since
5
+ appended new targeted suites, so those verdicts are stale. This runner
6
+ re-evaluates only the no-witness mutants, only on suites that are new
7
+ relative to the recorded verdict, and rewrites the class to `high_value`
8
+ (with the witness) when one of them kills.
9
+
10
+ Also re-checks the CORRECT kernel on every new suite: a suite that rejects
11
+ the correct implementation is invalid and is reported (its kills don't count).
12
+
13
+ Journal: results/recheck_<problem>.jsonl (resume-safe)
14
+ Usage: python3 recheck_nowitness.py [--worker P]
15
+ """
16
+ import ctypes
17
+ import json
18
+ import os
19
+ import subprocess
20
+ import sys
21
+
22
+ HERE = os.path.dirname(os.path.abspath(__file__))
23
+ sys.path.insert(0, HERE)
24
+ RESULTS = os.path.join(HERE, "results")
25
+
26
+ import kernels_def as K # noqa: E402
27
+ import problems_ext # noqa: E402,F401
28
+ import candidates_loader # noqa: E402
29
+ import mutator # noqa: E402
30
+ from nvrtc_tce import externc, compile_ptx, device_source # noqa: E402
31
+ from screen_mutants import (NvrtcKernel, compare, install_watchdog, # noqa: E402
32
+ kernel_name, pet_watchdog, ref_fn_for)
33
+
34
+ candidates_loader.load_accepted()
35
+ BASE_SUITES = {"T0_original", "T1_signed", "T2_large", "T3_misaligned"}
36
+ SHARD_ID = int(os.environ.get("SHARD_ID", "0"))
37
+ SHARD_N = int(os.environ.get("SHARD_N", "1"))
38
+
39
+
40
+ def my_problems():
41
+ import hashlib
42
+ return [p for p in K.PROBLEMS
43
+ if int(hashlib.md5(p.encode()).hexdigest()[:8], 16) % SHARD_N == SHARD_ID]
44
+
45
+
46
+ def nowitness_ids(problem):
47
+ path = os.path.join(RESULTS, f"screen_{problem}.jsonl")
48
+ if not os.path.exists(path):
49
+ return set()
50
+ ids = set()
51
+ for line in open(path):
52
+ r = json.loads(line)
53
+ if r["type"] == "RESULT":
54
+ if r["cls"] == "no_witness":
55
+ ids.add(r["id"])
56
+ else:
57
+ ids.discard(r["id"])
58
+ return ids
59
+
60
+
61
+ def worker(problem):
62
+ install_watchdog()
63
+ import torch
64
+ ids = nowitness_ids(problem)
65
+ if not ids:
66
+ return
67
+ suites = [(n, b) for n, _, b in K.PROBLEMS[problem]["suites"]()
68
+ if n not in BASE_SUITES]
69
+ if not suites:
70
+ return
71
+
72
+ jpath = os.path.join(RESULTS, f"recheck_{problem}.jsonl")
73
+ done, pending = set(), None
74
+ if os.path.exists(jpath):
75
+ for line in open(jpath):
76
+ r = json.loads(line)
77
+ if r["type"] == "RSTART":
78
+ pending = (r["id"], r["suite"])
79
+ elif r["type"] == "RCELL":
80
+ done.add((r["id"], r["suite"]))
81
+ pending = None
82
+ journal = open(jpath, "a")
83
+
84
+ def emit(**rec):
85
+ journal.write(json.dumps(rec) + "\n")
86
+ journal.flush()
87
+ os.fsync(journal.fileno())
88
+
89
+ if pending is not None:
90
+ emit(type="RCELL", id=pending[0], suite=pending[1],
91
+ outcome="killed", reason="crash")
92
+ done.add(pending)
93
+
94
+ _ms = list(mutator.generate(problem, device_source(K.PROBLEMS[problem]["cuda"])))
95
+ _cap = int(os.environ.get("MUTANT_CAP", "0"))
96
+ if _cap:
97
+ _ms = mutator.stratified_sample(_ms, _cap) # same sample as screening
98
+ mutants = {m["id"]: m for m in _ms}
99
+ ref_fn = ref_fn_for(problem)
100
+ torch.zeros(1, device="cuda")
101
+ cuda_lib = ctypes.CDLL("libcuda.so.1")
102
+ correct_src = externc(device_source(K.PROBLEMS[problem]["cuda"]))
103
+ try:
104
+ ptx_cache = {"__correct__": compile_ptx(correct_src, "c.cu")}
105
+ except RuntimeError:
106
+ emit(type="RDONE", problem=problem, skipped="correct_compile_fail")
107
+ journal.close()
108
+ return
109
+
110
+ for sname, builder in suites:
111
+ # validity gate first: the suite must not reject the correct kernel
112
+ gpu_in = [t.cuda() for t in builder(0)]
113
+ with torch.no_grad():
114
+ ref = ref_fn(*gpu_in) # keep on GPU: CPU round-trips dominated runtime
115
+ try:
116
+ kern = NvrtcKernel(cuda_lib, ptx_cache["__correct__"], kernel_name(problem))
117
+ except RuntimeError as e:
118
+ emit(type="VALID", suite=sname, valid=False, detail=f"load_fail {e}")
119
+ del gpu_in, ref
120
+ torch.cuda.empty_cache()
121
+ continue
122
+ pet_watchdog()
123
+ out = kern.launch(problem, gpu_in, torch)
124
+ valid = compare(ref, out, torch) == "survived"
125
+ kern.unload()
126
+ del out
127
+ emit(type="VALID", suite=sname, valid=valid)
128
+ if not valid:
129
+ del gpu_in, ref
130
+ torch.cuda.empty_cache()
131
+ continue
132
+
133
+ for mid in sorted(ids):
134
+ if (mid, sname) in done or mid not in mutants:
135
+ continue
136
+ if mid not in ptx_cache:
137
+ src = externc(mutants[mid]["src"])
138
+ try:
139
+ ptx_cache[mid] = compile_ptx(src, "m.cu")
140
+ except RuntimeError:
141
+ continue
142
+ emit(type="RSTART", id=mid, suite=sname)
143
+ try:
144
+ kern = NvrtcKernel(cuda_lib, ptx_cache[mid], kernel_name(problem))
145
+ except RuntimeError as e:
146
+ emit(type="RCELL", id=mid, suite=sname, outcome="load_fail",
147
+ detail=str(e)[:50])
148
+ continue
149
+ try:
150
+ pet_watchdog()
151
+ out = kern.launch(problem, gpu_in, torch)
152
+ r = compare(ref, out, torch)
153
+ del out
154
+ kern.unload()
155
+ except RuntimeError as e:
156
+ emit(type="RCELL", id=mid, suite=sname, outcome="killed",
157
+ reason="crash", detail=str(e)[:60])
158
+ journal.close()
159
+ sys.exit(3)
160
+ emit(type="RCELL", id=mid, suite=sname,
161
+ outcome="survived" if r == "survived" else "killed")
162
+ del gpu_in, ref
163
+ torch.cuda.empty_cache()
164
+ emit(type="RDONE", problem=problem)
165
+ journal.close()
166
+
167
+
168
+ def summary():
169
+ import collections
170
+ conv = collections.Counter()
171
+ invalid = []
172
+ for f in os.listdir(RESULTS):
173
+ if not f.startswith("recheck_"):
174
+ continue
175
+ p = f[8:-6]
176
+ killed = set()
177
+ for line in open(os.path.join(RESULTS, f)):
178
+ r = json.loads(line)
179
+ if r["type"] == "RCELL" and r["outcome"] == "killed":
180
+ killed.add(r["id"])
181
+ elif r["type"] == "VALID" and not r["valid"]:
182
+ invalid.append((p, r["suite"]))
183
+ conv[p] = len(killed)
184
+ tot_before = sum(len(nowitness_ids(p)) for p in conv)
185
+ print(f"no-witness mutants re-tested: {tot_before}")
186
+ print(f"newly killed (-> high_value): {sum(conv.values())}")
187
+ if tot_before:
188
+ print(f"conversion rate: {sum(conv.values())/tot_before:.1%}")
189
+ print(f"invalid suites (reject correct kernel): {len(invalid)}")
190
+ for p, s in invalid[:10]:
191
+ print(f" {p} / {s}")
192
+ for p, n in conv.most_common(10):
193
+ print(f" {p:32s} +{n}")
194
+
195
+
196
+ def orchestrate():
197
+ for problem in my_problems():
198
+ if not nowitness_ids(problem):
199
+ continue
200
+ for attempt in range(40):
201
+ try:
202
+ rc = subprocess.run([sys.executable, __file__, "--worker", problem],
203
+ timeout=2400).returncode
204
+ except subprocess.TimeoutExpired:
205
+ print(f"[recheck] {problem}: TIMEOUT", flush=True)
206
+ rc = 0
207
+ if rc == 0:
208
+ break
209
+ print(f"[recheck] {problem}: done", flush=True)
210
+ summary()
211
+ print("[recheck] ALL DONE", flush=True)
212
+
213
+
214
+ if __name__ == "__main__":
215
+ if len(sys.argv) > 2 and sys.argv[1] == "--worker":
216
+ worker(sys.argv[2])
217
+ elif len(sys.argv) > 1 and sys.argv[1] == "--summary":
218
+ summary()
219
+ else:
220
+ orchestrate()
pipeline/sanitizer_probe.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run one mutant once on a small input (for compute-sanitizer memcheck).
2
+ Usage: sanitizer_probe.py <problem> <mutant_id>"""
3
+ import ctypes
4
+ import os
5
+ import sys
6
+
7
+ HERE = os.path.dirname(os.path.abspath(__file__))
8
+ sys.path.insert(0, HERE)
9
+
10
+ import torch # noqa: E402
11
+
12
+ import kernels_def as K # noqa: E402
13
+ import problems_ext # noqa: E402,F401
14
+ import mutator # noqa: E402
15
+ from adjudicate import rand_inputs # noqa: E402
16
+ from nvrtc_tce import compile_ptx, device_source # noqa: E402
17
+ from screen_mutants import NvrtcKernel, kernel_name # noqa: E402
18
+
19
+ problem, mid = sys.argv[1], sys.argv[2]
20
+ m = {x["id"]: x for x in
21
+ mutator.generate(problem, device_source(K.PROBLEMS[problem]["cuda"]))}[mid]
22
+ src = m["src"].replace("__global__ void", 'extern "C" __global__ void')
23
+ torch.zeros(1, device="cuda")
24
+ kern = NvrtcKernel(ctypes.CDLL("libcuda.so.1"), compile_ptx(src, "m.cu"),
25
+ kernel_name(problem))
26
+ gpu_in = [x.cuda() for x in rand_inputs(problem, 0, torch)]
27
+ out = kern.launch(problem, gpu_in, torch)
28
+ torch.cuda.synchronize()
29
+ print("probe done", out.shape)
pipeline/screen_mutants.py ADDED
@@ -0,0 +1,534 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Screening pipeline: universal-mutator mutants -> NVRTC compile -> TCE dedup
2
+ -> GPU kill screening -> value classification.
3
+
4
+ Classification per mutant:
5
+ compile_fail nvrtc rejected it (discarded, that's the filter working)
6
+ tce_equiv_correct PTX identical to correct kernel (host-only or no-op)
7
+ tce_dup PTX identical to an earlier mutant (behavioral duplicate)
8
+ killed_by_T0 original KernelBench inputs already catch it (low value)
9
+ high_value survives T0, killed by a targeted input (witness recorded)
10
+ no_witness survives everything we have (equivalent / oracle-blind)
11
+
12
+ Runs entirely on the NVRTC + driver-API fast path (no torch extensions).
13
+ Orchestrator mode (default) spawns one worker subprocess per problem and
14
+ respawns on CUDA-poisoned exits; worker mode (--worker PROB) does the work.
15
+
16
+ T0 is run with 2 seeds instead of KernelBench's 5: survival was shown to be
17
+ deterministic w.r.t. reseeding in the validation experiment.
18
+ """
19
+ import ctypes
20
+ import json
21
+ import os
22
+ import subprocess
23
+ import sys
24
+ import time
25
+
26
+ HERE = os.path.dirname(os.path.abspath(__file__))
27
+ sys.path.insert(0, HERE)
28
+ RESULTS = os.path.join(HERE, "results")
29
+
30
+ import kernels_def as K # noqa: E402
31
+ import problems_ext # noqa: E402,F401 (registers extra problems)
32
+ import mutator # noqa: E402
33
+ from nvrtc_tce import externc, compile_ptx, device_source, normalized_hash # noqa: E402
34
+
35
+ ATOL = RTOL = 1e-2
36
+ MUTANT_CAP = int(os.environ.get("MUTANT_CAP", "0")) # 0 = no cap
37
+ PROBLEM_TIMEOUT = 1800 # wall-clock cap per problem per attempt
38
+ # Shard support: SHARD_ID/SHARD_N split problems across independent processes
39
+ # (each on its own GPU). Journals are per-problem files, so shards never
40
+ # contend; a crash in one shard cannot stall the others.
41
+ SHARD_ID = int(os.environ.get("SHARD_ID", "0"))
42
+ SHARD_N = int(os.environ.get("SHARD_N", "1"))
43
+
44
+
45
+ STEAL = os.environ.get("STEAL", "0") == "1"
46
+
47
+
48
+ def _has_done_marker(problem):
49
+ path = os.path.join(RESULTS, f"screen_{problem}.jsonl")
50
+ if not os.path.exists(path):
51
+ return False
52
+ txt = open(path).read()
53
+ # PROBE_DONE means only the quarantine phase finished; treating it as
54
+ # complete made every gave-up-era problem invisible to STEAL mode
55
+ return '"DONE"' in txt
56
+
57
+
58
+ def my_problems():
59
+ """Own shard's slice; in STEAL mode, instead take any problem that has no
60
+ completion marker yet (idle GPUs help finish the tail). A claim file makes
61
+ two stealers unlikely to pick the same problem; if they do, journals still
62
+ dedupe by mutant id so the work is merely repeated, never corrupted."""
63
+ import hashlib
64
+ if STEAL:
65
+ out = []
66
+ for p in K.PROBLEMS:
67
+ if _has_done_marker(p):
68
+ continue
69
+ claim = os.path.join(RESULTS, f".claim_{p}")
70
+ # a stale claim from a crashed run must not hide the problem
71
+ # forever: reclaim anything older than 45 minutes
72
+ try:
73
+ if time.time() - os.path.getmtime(claim) > 2700:
74
+ os.unlink(claim)
75
+ except OSError:
76
+ pass
77
+ try:
78
+ fd = os.open(claim, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
79
+ os.write(fd, str(SHARD_ID).encode())
80
+ os.close(fd)
81
+ out.append(p)
82
+ except FileExistsError:
83
+ continue
84
+ return out
85
+ out = []
86
+ for p in K.PROBLEMS:
87
+ h = int(hashlib.md5(p.encode()).hexdigest()[:8], 16)
88
+ if h % SHARD_N == SHARD_ID:
89
+ out.append(p)
90
+ return out
91
+
92
+ REF_FN = {
93
+ "relu": lambda x: __import__("torch").relu(x),
94
+ "matmul": lambda a, b: __import__("torch").matmul(a, b),
95
+ "softmax": lambda x: __import__("torch").softmax(x, dim=1),
96
+ "sum": lambda x: __import__("torch").sum(x, dim=1, keepdim=True),
97
+ }
98
+ KERNEL_NAME = {"relu": "relu_kernel", "matmul": "matmul_kernel",
99
+ "softmax": "softmax_kernel", "sum": "sum_dim1_kernel"}
100
+
101
+
102
+ def probe_suites(problem, torch):
103
+ """Tiny inputs for crash quarantine. First entry MUST be T0-like
104
+ (aligned shape, rand[0,1)) — a crash there predicts a crash on real T0.
105
+ Values are never compared in the probe; only crash/no-crash matters."""
106
+ reg = K.PROBLEMS[problem].get("probe")
107
+ if reg is not None:
108
+ return reg(torch)
109
+ torch.manual_seed(0)
110
+ if problem == "relu":
111
+ return [("p_aligned", [torch.rand(32, 256)]),
112
+ ("p_misaligned", [torch.randn(7, 257)])]
113
+ if problem == "matmul":
114
+ return [("p_aligned", [torch.rand(128, 128), torch.rand(128, 128)]),
115
+ ("p_misaligned", [torch.randn(67, 67), torch.randn(67, 67)])]
116
+ if problem == "softmax":
117
+ x = torch.randn(16, 259) * 0.01
118
+ x[:, -1] = 20.0
119
+ return [("p_aligned", [torch.rand(16, 512)]),
120
+ ("p_large", [torch.randn(16, 512) * 100.0]),
121
+ ("p_misaligned_spike", [x])]
122
+ if problem == "sum":
123
+ return [("p_aligned", [torch.rand(4, 64, 256)]),
124
+ ("p_misaligned", [torch.randn(4, 64, 255)])]
125
+ raise ValueError(problem)
126
+
127
+
128
+ _WD = {"deadline": None}
129
+
130
+
131
+ def install_watchdog(seconds=180):
132
+ """Thread-based watchdog. A mutated kernel can spin forever; the process
133
+ then blocks inside cuLaunchKernel/synchronize, which are C calls. Python
134
+ signal handlers CANNOT run while the main thread is inside such a call
135
+ (the handler is deferred until the call returns, which never happens), so
136
+ signal.alarm is useless here. A daemon thread works because ctypes/torch
137
+ release the GIL around those calls, letting the watchdog run and hard-exit.
138
+ The orchestrator respawns us; the dangling START/PSTART journal entry is
139
+ recorded as a kill, which is the correct verdict for a non-terminating
140
+ kernel."""
141
+ import threading
142
+ import time as _time
143
+
144
+ def _loop():
145
+ while True:
146
+ _time.sleep(5)
147
+ dl = _WD["deadline"]
148
+ if dl is not None and _time.monotonic() > dl:
149
+ os.write(2, b"WATCHDOG: kernel hang, aborting process\n")
150
+ os._exit(3)
151
+
152
+ _WD["deadline"] = None
153
+ t = threading.Thread(target=_loop, daemon=True)
154
+ t.start()
155
+
156
+
157
+ def pet_watchdog(seconds=180):
158
+ import time as _time
159
+ _WD["deadline"] = _time.monotonic() + seconds
160
+
161
+
162
+ def kernel_name(problem):
163
+ return K.PROBLEMS[problem].get("kernel_name") or KERNEL_NAME[problem]
164
+
165
+
166
+ def ref_fn_for(problem):
167
+ return K.PROBLEMS[problem].get("ref") or REF_FN[problem]
168
+
169
+
170
+ def launch_spec(problem, inputs, torch):
171
+ """Return (out_tensor, grid(3), block(3), scalar_args:list[(ctype, value)])."""
172
+ reg = K.PROBLEMS[problem].get("launch")
173
+ if reg is not None:
174
+ return reg(inputs, torch)
175
+ if problem == "relu":
176
+ x = inputs[0]
177
+ out = torch.zeros_like(x)
178
+ n = x.numel()
179
+ return out, ((n + 255) // 256, 1, 1), (256, 1, 1), [(ctypes.c_longlong, n)]
180
+ if problem == "matmul":
181
+ A, B = inputs
182
+ N = A.shape[0]
183
+ out = torch.zeros((N, N), device=A.device, dtype=A.dtype)
184
+ g = (N + 31) // 32
185
+ return out, (g, g, 1), (32, 32, 1), [(ctypes.c_int, N)]
186
+ if problem == "softmax":
187
+ x = inputs[0]
188
+ out = torch.zeros_like(x)
189
+ return out, (x.shape[0], 1, 1), (256, 1, 1), [(ctypes.c_int, x.shape[1])]
190
+ if problem == "sum":
191
+ x = inputs[0]
192
+ B, R, C = x.shape
193
+ out = torch.zeros((B, 1, C), device=x.device, dtype=x.dtype)
194
+ return out, ((C + 255) // 256, B, 1), (256, 1, 1), \
195
+ [(ctypes.c_int, B), (ctypes.c_int, R), (ctypes.c_int, C)]
196
+ raise ValueError(problem)
197
+
198
+
199
+ class NvrtcKernel:
200
+ def __init__(self, cuda_lib, ptx, kname):
201
+ self.cuda = cuda_lib
202
+ self.module = ctypes.c_void_p()
203
+ rc = self.cuda.cuModuleLoadData(ctypes.byref(self.module), (ptx.encode() if isinstance(ptx, str) else ptx))
204
+ if rc != 0:
205
+ raise RuntimeError(f"cuModuleLoadData rc={rc}")
206
+ # multi-kernel substrates (level3 architectures) expose one __global__
207
+ # per layer, so a mutation lands in a specific layer and we can measure
208
+ # how far a fault propagates through depth.
209
+ self.funcs = {}
210
+ names = kname if isinstance(kname, (list, tuple)) else [kname]
211
+ for nm in names:
212
+ f = ctypes.c_void_p()
213
+ rc = self.cuda.cuModuleGetFunction(ctypes.byref(f), self.module,
214
+ nm.encode())
215
+ if rc != 0:
216
+ raise RuntimeError(f"cuModuleGetFunction({nm}) rc={rc}")
217
+ self.funcs[nm] = f
218
+ self.func = self.funcs[names[0]]
219
+
220
+ def _raw_launch(self, func, grid, block, tensors, scalars, torch):
221
+ holders = [ctypes.c_void_p(t.data_ptr()) for t in tensors]
222
+ for ct, v in scalars:
223
+ holders.append(ct(v))
224
+ args = (ctypes.c_void_p * len(holders))(
225
+ *[ctypes.cast(ctypes.byref(h), ctypes.c_void_p) for h in holders])
226
+ rc = self.cuda.cuLaunchKernel(func, *grid, *block, 0, None, args, None)
227
+ if rc != 0:
228
+ raise RuntimeError(f"cuLaunchKernel rc={rc}")
229
+
230
+ def launch(self, problem, inputs, torch):
231
+ spec = launch_spec(problem, inputs, torch)
232
+ if isinstance(spec, dict): # multi-kernel pipeline
233
+ for step in spec["seq"]:
234
+ fname, grid, block, tensors, scalars = step
235
+ self._raw_launch(self.funcs[fname], grid, block, tensors,
236
+ scalars, torch)
237
+ torch.cuda.synchronize()
238
+ return spec["out"]
239
+ out, grid, block, scalars = spec
240
+ holders = []
241
+ for t in inputs:
242
+ holders.append(ctypes.c_void_p(t.data_ptr()))
243
+ holders.append(ctypes.c_void_p(out.data_ptr()))
244
+ for ct, v in scalars:
245
+ holders.append(ct(v))
246
+ args = (ctypes.c_void_p * len(holders))(
247
+ *[ctypes.cast(ctypes.byref(h), ctypes.c_void_p) for h in holders])
248
+ rc = self.cuda.cuLaunchKernel(self.func, *grid, *block, 0, None, args, None)
249
+ if rc != 0:
250
+ raise RuntimeError(f"cuLaunchKernel rc={rc}")
251
+ torch.cuda.synchronize()
252
+ return out
253
+
254
+ def unload(self):
255
+ self.cuda.cuModuleUnload(self.module)
256
+
257
+
258
+ def compare(ref, out, torch):
259
+ if out.shape != ref.shape:
260
+ return "shape_mismatch"
261
+ if torch.allclose(ref, out, atol=ATOL, rtol=RTOL):
262
+ return "survived"
263
+ return "value_mismatch"
264
+
265
+
266
+ def load_journal(journal_path):
267
+ """Returns (done RESULTs, probe outcomes, dangling START, dangling PSTART)."""
268
+ done, probes, pend_s, pend_p = {}, {}, None, None
269
+ if os.path.exists(journal_path):
270
+ for line in open(journal_path):
271
+ r = json.loads(line)
272
+ if r["type"] == "START":
273
+ pend_s = r
274
+ elif r["type"] == "RESULT":
275
+ done[r["id"]] = r
276
+ pend_s = None
277
+ elif r["type"] == "PSTART":
278
+ pend_p = r
279
+ elif r["type"] == "PROBE":
280
+ probes[r["id"]] = r["outcome"]
281
+ pend_p = None
282
+ return done, probes, pend_s, pend_p
283
+
284
+
285
+ def compile_and_tce(problem, done, emit):
286
+ """Compile all pending mutants, classify compile_fail/TCE, return kept list."""
287
+ src_correct = externc(device_source(K.PROBLEMS[problem]["cuda"]))
288
+ mutants = list(mutator.generate(problem, device_source(K.PROBLEMS[problem]["cuda"])))
289
+ if MUTANT_CAP:
290
+ # multi-kernel level-3 substrates emit thousands of mutants per problem;
291
+ # sample per (rule, layer) so every rule family AND every network layer
292
+ # stays represented while the pool stays affordable
293
+ mutants = mutator.stratified_sample(mutants, MUTANT_CAP)
294
+ for m in mutants:
295
+ m["src"] = m["src"].replace("__global__ void", 'extern "C" __global__ void')
296
+ h_correct = normalized_hash(compile_ptx(src_correct, "correct.cu"))
297
+ seen_hash, compiled = {}, []
298
+ for m in mutants:
299
+ try:
300
+ ptx = compile_ptx(m["src"], "m.cu")
301
+ except RuntimeError:
302
+ if m["id"] not in done:
303
+ emit(type="RESULT", id=m["id"], cls="compile_fail",
304
+ rule=m["rule"], category=m["category"], site=m["site"])
305
+ continue
306
+ h = normalized_hash(ptx)
307
+ if h == h_correct:
308
+ if m["id"] not in done:
309
+ emit(type="RESULT", id=m["id"], cls="tce_equiv_correct",
310
+ rule=m["rule"], category=m["category"], site=m["site"])
311
+ continue
312
+ if h in seen_hash:
313
+ if m["id"] not in done:
314
+ emit(type="RESULT", id=m["id"], cls="tce_dup", dup_of=seen_hash[h],
315
+ rule=m["rule"], category=m["category"], site=m["site"])
316
+ continue
317
+ seen_hash[h] = m["id"]
318
+ compiled.append((m, ptx))
319
+ return compiled
320
+
321
+
322
+ def probe(problem):
323
+ install_watchdog()
324
+ """Crash quarantine pass: launch every mutant on tiny inputs only.
325
+ Crashers are caught here where a respawn costs seconds, not a cache rebuild."""
326
+ import torch
327
+ journal_path = os.path.join(RESULTS, f"screen_{problem}.jsonl")
328
+ done, probes, _, pend_p = load_journal(journal_path)
329
+ journal = open(journal_path, "a")
330
+
331
+ def emit(**rec):
332
+ journal.write(json.dumps(rec) + "\n")
333
+ journal.flush()
334
+ os.fsync(journal.fileno())
335
+
336
+ if pend_p is not None:
337
+ emit(type="PROBE", id=pend_p["id"], outcome=f"crash:{pend_p['suite']}")
338
+ probes[pend_p["id"]] = "x"
339
+
340
+ compiled = compile_and_tce(problem, done, emit)
341
+ todo = [(m, p) for m, p in compiled if m["id"] not in done and m["id"] not in probes]
342
+ if not todo:
343
+ emit(type="PROBE_DONE", problem=problem)
344
+ return
345
+
346
+ torch.zeros(1, device="cuda")
347
+ cuda_lib = ctypes.CDLL("libcuda.so.1")
348
+ gpu_suites = [(n, [t.cuda() for t in ins]) for n, ins in probe_suites(problem, torch)]
349
+
350
+ for m, ptx in todo:
351
+ try:
352
+ kern = NvrtcKernel(cuda_lib, ptx, kernel_name(problem))
353
+ except RuntimeError as e:
354
+ # module load rejected (e.g. rc=222 PTX/driver mismatch): treat as
355
+ # a compile failure for this mutant, never as a shard-fatal error
356
+ emit(type="PROBE", id=m["id"], outcome="load_fail",
357
+ detail=str(e)[:60])
358
+ continue
359
+ crashed = False
360
+ for sname, gpu_in in gpu_suites:
361
+ emit(type="PSTART", id=m["id"], suite=sname)
362
+ try:
363
+ pet_watchdog()
364
+ out = kern.launch(problem, gpu_in, torch)
365
+ del out
366
+ except RuntimeError as e:
367
+ emit(type="PROBE", id=m["id"], outcome=f"crash:{sname}",
368
+ detail=str(e)[:80])
369
+ journal.close()
370
+ sys.exit(3)
371
+ kern.unload()
372
+ emit(type="PROBE", id=m["id"], outcome="clean")
373
+ emit(type="PROBE_DONE", problem=problem)
374
+
375
+
376
+ def worker(problem):
377
+ install_watchdog()
378
+ import torch
379
+ journal_path = os.path.join(RESULTS, f"screen_{problem}.jsonl")
380
+ done, probes, pending, _ = load_journal(journal_path)
381
+ journal = open(journal_path, "a")
382
+
383
+ def emit(**rec):
384
+ journal.write(json.dumps(rec) + "\n")
385
+ journal.flush()
386
+ os.fsync(journal.fileno())
387
+
388
+ # previous process died mid-eval: the running suite is the killer
389
+ if pending is not None:
390
+ cls = "killed_by_T0" if pending["suite"] == "T0_original" else "high_value"
391
+ emit(type="RESULT", id=pending["id"], cls=cls, reason="cuda_poisoned",
392
+ witness=None if cls == "killed_by_T0" else pending["suite"])
393
+ done[pending["id"]] = True
394
+
395
+ compiled = [(m, p) for m, p in compile_and_tce(problem, done, emit)
396
+ if m["id"] not in done]
397
+ if not compiled:
398
+ emit(type="DONE", problem=problem)
399
+ return
400
+
401
+ # suites: T0 capped at 2 trials, then targeted
402
+ suites = [(n, min(t, 2), b) for n, t, b in K.PROBLEMS[problem]["suites"]()]
403
+ ref_fn = ref_fn_for(problem)
404
+ cache = {}
405
+
406
+ def get_pair(suite_name, builder, trial):
407
+ key = (suite_name, trial)
408
+ if key not in cache:
409
+ cpu_in = builder(trial)
410
+ gpu_in = [t.cuda() for t in cpu_in]
411
+ with torch.no_grad():
412
+ ref = ref_fn(*gpu_in)
413
+ cache[key] = (gpu_in, ref)
414
+ return cache[key]
415
+
416
+ cuda_lib = ctypes.CDLL("libcuda.so.1")
417
+ torch.zeros(1, device="cuda") # init context
418
+
419
+ for m, ptx in compiled:
420
+ outcome = probes.get(m["id"], "clean")
421
+ if outcome == "crash:p_aligned":
422
+ # crashed on a tiny T0-like input -> would crash on real T0
423
+ emit(type="RESULT", id=m["id"], cls="killed_by_T0", reason="probe_crash",
424
+ witness=None, rule=m["rule"], category=m["category"], site=m["site"])
425
+ continue
426
+ t0_only = outcome.startswith("crash:")
427
+ probe_witness = outcome.split(":", 1)[1] if t0_only else None
428
+
429
+ current_suite = "T0_original"
430
+ emit(type="START", id=m["id"], suite=current_suite)
431
+ try:
432
+ kern = NvrtcKernel(cuda_lib, ptx, kernel_name(problem))
433
+ except RuntimeError as e:
434
+ emit(type="RESULT", id=m["id"], cls="compile_fail",
435
+ rule=m["rule"], category=m["category"], site=m["site"],
436
+ detail=str(e)[:60])
437
+ continue
438
+ cls, witness = None, None
439
+ try:
440
+ killed_t0 = False
441
+ name0, t0_trials, b0 = suites[0]
442
+ for trial in range(t0_trials):
443
+ gpu_in, ref = get_pair(name0, b0, trial)
444
+ pet_watchdog()
445
+ out = kern.launch(problem, gpu_in, torch)
446
+ r = compare(ref, out, torch)
447
+ del out
448
+ if r != "survived":
449
+ killed_t0 = True
450
+ break
451
+ if killed_t0:
452
+ cls = "killed_by_T0"
453
+ elif t0_only:
454
+ # survives T0 but a targeted probe input crashes it
455
+ cls, witness = "high_value", f"probe:{probe_witness}"
456
+ else:
457
+ for sname, strials, sbuilder in suites[1:]:
458
+ current_suite = sname
459
+ emit(type="START", id=m["id"], suite=sname)
460
+ for trial in range(strials):
461
+ gpu_in, ref = get_pair(sname, sbuilder, trial)
462
+ pet_watchdog()
463
+ out = kern.launch(problem, gpu_in, torch)
464
+ r = compare(ref, out, torch)
465
+ del out
466
+ if r != "survived":
467
+ witness = sname
468
+ break
469
+ if witness:
470
+ break
471
+ cls = "high_value" if witness else "no_witness"
472
+ kern.unload()
473
+ except RuntimeError as e:
474
+ # CUDA launch/sync failure: the crashing suite is the kill witness.
475
+ # Context may be poisoned -> record and let orchestrator respawn us.
476
+ cls = "killed_by_T0" if current_suite == "T0_original" else "high_value"
477
+ emit(type="RESULT", id=m["id"], cls=cls, reason="crash",
478
+ witness=None if current_suite == "T0_original" else current_suite,
479
+ rule=m["rule"], category=m["category"], site=m["site"],
480
+ detail=str(e)[:120])
481
+ journal.close()
482
+ sys.exit(3)
483
+ emit(type="RESULT", id=m["id"], cls=cls, witness=witness,
484
+ rule=m["rule"], category=m["category"], site=m["site"])
485
+
486
+ emit(type="DONE", problem=problem)
487
+
488
+
489
+ def orchestrate():
490
+ """Registry stays resident here; each problem's probe and screening pass
491
+ run in forked children, so a poisoned CUDA context or a watchdog kill costs
492
+ a fork (microseconds) instead of an 85s registry re-import."""
493
+ from forkpool import run_isolated
494
+ for problem in my_problems():
495
+ # crash-quarantine churn is HEALTHY (each crashing mutant costs one
496
+ # respawn and journals progress); a deterministic hang outside mutant
497
+ # testing journals NOTHING. So give up only after several consecutive
498
+ # attempts with zero journal growth, not after N attempts total.
499
+ jpath = os.path.join(RESULTS, f"screen_{problem}.jsonl")
500
+
501
+ def jsize():
502
+ try:
503
+ return os.path.getsize(jpath)
504
+ except OSError:
505
+ return 0
506
+
507
+ def run_phase(fn, max_attempts):
508
+ stuck, prev = 0, jsize()
509
+ for attempt in range(max_attempts):
510
+ rc = run_isolated(fn, problem, timeout=PROBLEM_TIMEOUT)
511
+ if rc in (0, 124):
512
+ return True
513
+ cur = jsize()
514
+ stuck = stuck + 1 if cur == prev else 0
515
+ prev = cur
516
+ if stuck >= 4:
517
+ return False
518
+ return False
519
+
520
+ ok = run_phase(probe, 600)
521
+ print(f"[screen] {problem}: probe done", flush=True)
522
+ ok = ok and run_phase(worker, 400)
523
+ print(f"[screen] {problem}: "
524
+ f"{'done' if ok else 'GAVE UP (no journal progress)'}", flush=True)
525
+ print("[screen] ALL DONE", flush=True)
526
+
527
+
528
+ if __name__ == "__main__":
529
+ if len(sys.argv) > 2 and sys.argv[1] == "--worker":
530
+ worker(sys.argv[2])
531
+ elif len(sys.argv) > 2 and sys.argv[1] == "--probe":
532
+ probe(sys.argv[2])
533
+ else:
534
+ orchestrate()
pipeline/suite_filter.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Blocklist of invalid test suites.
2
+
3
+ A suite is INVALID if it makes the CORRECT kernel fail the benchmark's own
4
+ check — such an input would reject valid submissions, so any mutant it
5
+ "kills" must not be counted. The recheck stage records these as
6
+ VALID/valid=false; this module turns those records into a blocklist that
7
+ every downstream stage (full matrix, audit, set-cover) consults, so invalid
8
+ suites are filtered out at load time rather than by rewriting generated code.
9
+
10
+ Usage:
11
+ from suite_filter import valid_suites
12
+ for name, trials, builder in valid_suites(problem): ...
13
+ """
14
+ import json
15
+ import os
16
+
17
+ HERE = os.path.dirname(os.path.abspath(__file__))
18
+ RESULTS = os.path.join(HERE, "results")
19
+ BLOCKLIST = os.path.join(RESULTS, "invalid_suites.json")
20
+
21
+ _cache = None
22
+
23
+
24
+ def refresh():
25
+ """Rebuild the blocklist from recheck journals. Returns {problem: [suite]}."""
26
+ bad = {}
27
+ for f in os.listdir(RESULTS):
28
+ if not (f.startswith("recheck_") and f.endswith(".jsonl")):
29
+ continue
30
+ problem = f[len("recheck_"):-len(".jsonl")]
31
+ for line in open(os.path.join(RESULTS, f)):
32
+ try:
33
+ r = json.loads(line)
34
+ except ValueError:
35
+ continue
36
+ if r.get("type") == "VALID" and not r.get("valid"):
37
+ bad.setdefault(problem, [])
38
+ if r["suite"] not in bad[problem]:
39
+ bad[problem].append(r["suite"])
40
+ with open(BLOCKLIST, "w") as fh:
41
+ json.dump(bad, fh, indent=1, sort_keys=True)
42
+ global _cache
43
+ _cache = bad
44
+ return bad
45
+
46
+
47
+ def blocked(problem):
48
+ global _cache
49
+ if _cache is None:
50
+ if os.path.exists(BLOCKLIST):
51
+ _cache = json.load(open(BLOCKLIST))
52
+ else:
53
+ _cache = refresh()
54
+ return set(_cache.get(problem, ()))
55
+
56
+
57
+ def valid_suites(problem):
58
+ """The problem's suites minus any that reject the correct implementation."""
59
+ import kernels_def as K
60
+ bad = blocked(problem)
61
+ return [(n, t, b) for n, t, b in K.PROBLEMS[problem]["suites"]()
62
+ if n not in bad]
63
+
64
+
65
+ if __name__ == "__main__":
66
+ bad = refresh()
67
+ n = sum(len(v) for v in bad.values())
68
+ print(f"invalid suites: {n} across {len(bad)} problems")
69
+ for p, s in sorted(bad.items(), key=lambda kv: -len(kv[1]))[:10]:
70
+ print(f" {p:34s} {s}")
pipeline/validate_ext.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Auto-validation gate for canonical kernels: the correct implementation must
2
+ survive every suite (T0 capped at 2 trials) before it may serve as a mutation
3
+ substrate. Exits nonzero on any failure so the pipeline aborts.
4
+
5
+ Usage: python3 validate_ext.py [problem ...] (default: extended problems only)
6
+ """
7
+ import ctypes
8
+ import sys
9
+
10
+ import torch
11
+
12
+ import kernels_def as K
13
+ import problems_ext # noqa: F401
14
+ from nvrtc_tce import compile_ptx, device_source
15
+ from screen_mutants import NvrtcKernel, compare, kernel_name, launch_spec, ref_fn_for
16
+
17
+ EXT = ["leakyrelu", "gelu", "sigmoid", "logsoftmax", "matmul_mk", "matmul_ta",
18
+ "mean", "max", "rmsnorm"]
19
+
20
+
21
+ def main():
22
+ problems = sys.argv[1:] or EXT
23
+ torch.zeros(1, device="cuda")
24
+ cuda_lib = ctypes.CDLL("libcuda.so.1")
25
+ failures = 0
26
+ for problem in problems:
27
+ src = device_source(K.PROBLEMS[problem]["cuda"]).replace(
28
+ "__global__ void", 'extern "C" __global__ void')
29
+ ptx = compile_ptx(src, f"{problem}.cu")
30
+ kern = NvrtcKernel(cuda_lib, ptx, kernel_name(problem))
31
+ ref_fn = ref_fn_for(problem)
32
+ for sname, n_trials, builder in K.PROBLEMS[problem]["suites"]():
33
+ for trial in range(min(n_trials, 2)):
34
+ inputs = builder(trial)
35
+ gpu_in = [t.cuda() for t in inputs]
36
+ with torch.no_grad():
37
+ ref = ref_fn(*gpu_in)
38
+ out = kern.launch(problem, gpu_in, torch)
39
+ r = compare(ref, out, torch)
40
+ status = "OK " if r == "survived" else "FAIL"
41
+ if r != "survived":
42
+ failures += 1
43
+ diff = (ref - out).abs().nan_to_num(nan=float("inf")).max()
44
+ print(f"[validate] {status} {problem}/{sname} t{trial}: {r} "
45
+ f"max_diff={float(diff):.4g}", flush=True)
46
+ else:
47
+ print(f"[validate] {status} {problem}/{sname} t{trial}", flush=True)
48
+ del gpu_in, ref, out
49
+ torch.cuda.empty_cache()
50
+ kern.unload()
51
+ print(f"[validate] failures: {failures}", flush=True)
52
+ sys.exit(1 if failures else 0)
53
+
54
+
55
+ if __name__ == "__main__":
56
+ main()
rules/BRIEF.md ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Rule-mining brief: new CUDA mutation operators
2
+
3
+ ## Context
4
+
5
+ We run mutation testing on CUDA kernels to measure how strong a benchmark's
6
+ correctness check is. Mutants are produced by DETERMINISTIC rewrite rules
7
+ applied to correct kernel source (see ../mutator.py for the 35 current rules
8
+ and the Rule dataclass). Each rule is (name, category, regex pattern,
9
+ replacement template). Every match site yields one mutant.
10
+
11
+ ## What makes a rule VALUABLE (this is the objective)
12
+
13
+ A mutant is "high value" when it (a) compiles, (b) SURVIVES the benchmark's
14
+ original test inputs — which are aligned shapes, torch.rand[0,1) values,
15
+ compared with allclose(atol=rtol=1e-2) — and (c) IS killable by some targeted
16
+ input (misaligned shape, signed values, large magnitude, structured spikes).
17
+
18
+ Measured value rates of existing rules on our pool:
19
+ ceil2floor 100%, const0to1 62%, sync2syncwarp 40%, loop-bound-minus1 39%,
20
+ loop-start-1 35%, sync-remove 36%, lt2le 21%, store-fp16 24%,
21
+ mul2plus 15%, mul2div 12% <- good
22
+ plus2minus 3%, guard-drop-ternary 0%, expf-fast 0%, smem-index-off1 0%,
23
+ fmin2fmax 0%, negate-store 0%, fdividef-fast 0% <- bad, being retired
24
+
25
+ Pattern: rules that break BOUNDARY handling, SYNCHRONIZATION, or PRECISION
26
+ produce faults invisible under aligned shapes and small positive values.
27
+ Rules that break gross semantics (a+b -> a-b) are caught immediately by any
28
+ input and are near-worthless.
29
+
30
+ ## Known expressiveness gaps (highest priority)
31
+
32
+ Our regex rules CANNOT express these, yet they are the most valuable faults:
33
+
34
+ 1. Identity substitution: replacing a call with its own argument, e.g.
35
+ `fmaxf(val, 0.0f)` -> `val` (removes a ReLU; invisible on positive inputs).
36
+ Generalize: any activation/clamp/saturation wrapper removal.
37
+ 2. Numerical-stability removal: dropping the max-subtraction in softmax-like
38
+ code, dropping epsilon in a denominator, dropping Kahan compensation.
39
+ 3. Partial-tail faults: processing only a prefix of a reduction, off-by-one
40
+ in the LAST iteration only, dropping the remainder loop after a vectorized
41
+ main loop.
42
+ 4. Accumulator staging: using the shared-memory value before the barrier,
43
+ re-initializing an accumulator inside the loop, double-counting an element.
44
+ 5. Index arithmetic that is wrong only at edges: swapping row/col strides in
45
+ ONE of several index expressions, using the wrong bound variable (M vs N),
46
+ using blockDim where gridDim is meant.
47
+
48
+ ## Your task
49
+
50
+ Write NEW rules into a fresh file: rules/mined_rules.py
51
+
52
+ Format (import-safe, no side effects):
53
+
54
+ ```python
55
+ from mutator import Rule # dataclass(name, category, pattern, replacement, note)
56
+
57
+ MINED_RULES = [
58
+ Rule("name", "category", r"regex", r"replacement", "one-line rationale"),
59
+ ...
60
+ ]
61
+ ```
62
+
63
+ Requirements:
64
+ - 25+ new rules, none duplicating an existing rule in ../mutator.py.
65
+ - Categories: boundary | sync | precision | indexing | arithmetic | semantic.
66
+ - Patterns must be robust regexes that match the CUDA style used in
67
+ ../problems_batch2.py and ../substrates/accepted/*.py (read several of them
68
+ — that is the corpus these rules must fire on).
69
+ - Prefer rules targeting the five gap families above; a regex CAN express
70
+ identity substitution when the call and its first argument are both simple
71
+ (e.g. r"fmaxf\((\w+), 0\.0f\)" -> r"\1"). Write several such families.
72
+ - Every rule must produce COMPILABLE code (mind types and parens).
73
+ - Avoid rules whose mutants would be caught by any input (gross semantics).
74
+ - Add a short comment block at the top summarizing your reasoning.
75
+
76
+ Verify before finishing: run
77
+ python3 -c "import sys; sys.path.insert(0,'.'); from rules.mined_rules import MINED_RULES; print(len(MINED_RULES))"
78
+ from the experiment directory, and also verify each pattern compiles as a
79
+ regex. Do not modify any existing file.
rules/BRIEF3.md ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Brief 3: fine-grained mutation rules ONLY
2
+
3
+ ## The single objective
4
+
5
+ Write rules whose mutants SURVIVE the benchmark's original inputs. Nothing
6
+ else matters. A rule whose mutants die on the first input is worthless — we
7
+ already have too many of those and they are being retired.
8
+
9
+ The original inputs are, for essentially every task:
10
+ torch.rand(...) # uniform [0,1), all POSITIVE, small magnitude
11
+ aligned shapes # every dim divisible by 32 or 256
12
+ compared with allclose(atol=1e-2, rtol=1e-2) # 1% slack
13
+
14
+ So a mutant survives if and only if its behavioural difference is INVISIBLE
15
+ under that specific regime. Measured value rates from our pool prove the point:
16
+
17
+ SURVIVES (keep writing rules like these)
18
+ ceil2floor 100% remainder block never exists when aligned
19
+ const0to1 62% changed constant is masked by tolerance
20
+ sync2syncwarp 40% race is benign when all values are similar
21
+ loop-bound-minus1 39% one missing term of thousands < 1%
22
+ store-fp16 24% 1e-3 relative error < 1e-2 tolerance
23
+
24
+ DIES INSTANTLY (do NOT write more of these)
25
+ plus2minus 3% every output element changes
26
+ mul2div/mul2plus 12% same
27
+ fmax2fmin 0% same
28
+ guard-drop-ternary 0% crashes or changes everything
29
+
30
+ ## The four survival mechanisms — target these deliberately
31
+
32
+ 1. TOLERANCE ABSORPTION. The fault's error is real but under 1% of the output
33
+ magnitude. Examples: one term of a long reduction dropped or double
34
+ counted; a constant off in the 4th significant digit; an intermediate
35
+ rounded to fewer bits; a slightly different but nearly-equal formula
36
+ (expf(a)*expf(b) instead of expf(a+b), fma vs mul+add, x*0.5f vs x/2.0f
37
+ with a perturbation).
38
+
39
+ 2. INPUT-DOMAIN EVASION. The faulty path is never taken because the input is
40
+ positive, small and finite. Examples: a branch that only differs for
41
+ negative / >1 / very large / NaN / exactly-equal values; a clamp whose
42
+ bound is never reached; a sign-dependent shortcut; a sentinel that only
43
+ matters when all values share a sign.
44
+
45
+ 3. SHAPE-ALIGNMENT EVASION. The faulty code path only executes on a partial
46
+ block / remainder loop / edge tile, which does not exist when every
47
+ dimension is a multiple of the block size. Examples: remainder handling,
48
+ the last tile of a K-loop, an edge guard on the final row.
49
+
50
+ 4. BENIGN RACE. Removing or weakening synchronization only corrupts results
51
+ when the racing values differ substantially; under uniform [0,1) the stale
52
+ and fresh values are nearly equal. Examples: partial barrier, barrier moved
53
+ one statement, reading a shared slot one iteration early, using a
54
+ thread-local value where a reduced value is intended.
55
+
56
+ ## Constraints
57
+
58
+ - Deterministic regex rewrite, single site per mutant, must COMPILE.
59
+ - Must not be a duplicate of any rule in ../mutator.py, rules/mined_rules.py,
60
+ or rules/structural_rules.py (read all three).
61
+ - Patterns must fire on the corpus: read at least 6 files from
62
+ substrates/accepted/ plus problems_batch2.py before writing anything.
63
+ A rule that never matches is worthless — prefer patterns built from syntax
64
+ you have actually SEEN in those files.
65
+ - No rule that changes every output element. Before adding a rule, ask:
66
+ "under torch.rand input with aligned shapes, would the output differ by
67
+ more than 1%?" If yes, discard it.
68
+
69
+ ## Deliverable
70
+
71
+ rules/fine_rules.py:
72
+
73
+ ```python
74
+ from mutator import Rule
75
+ FINE_RULES = [
76
+ Rule("name", "category", r"pattern", r"replacement",
77
+ "why it survives the original inputs, and what input would kill it"),
78
+ ...
79
+ ]
80
+ ```
81
+
82
+ 30+ rules, categories: boundary | sync | precision | indexing | semantic.
83
+ Each note MUST state the survival mechanism (1-4 above) and the killer input.
84
+ Verify: every regex compiles, the module imports, and report how many of your
85
+ rules actually fire across the corpus (write a small throwaway check, do not
86
+ add it to the repo).
rules/fine_rules.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fine-grained mutations aimed at the benchmark's weak original oracle.
2
+
3
+ The patterns are deliberately tied to CUDA spellings present in the accepted
4
+ substrates or ``problems_batch2.py``. Each substitution changes one narrow
5
+ site and remains valid CUDA/C++.
6
+ """
7
+
8
+ from mutator import Rule
9
+
10
+
11
+ FINE_RULES = [
12
+ # Boundary faults: one tail lane or one term of a long reduction.
13
+ Rule("output-elements-one-extra-lane", "boundary",
14
+ r"if \(output_index >= output_elements\) return;",
15
+ r"if (output_index > output_elements) return;",
16
+ "Mechanism 3 (shape-alignment evasion): an exactly aligned launch has no lane at output_elements; a misaligned output plus a CUDA memory checker kills it."),
17
+ Rule("line-count-one-extra-lane", "boundary",
18
+ r"if \(line >= line_count\) return;",
19
+ r"if (line > line_count) return;",
20
+ "Mechanism 3 (shape-alignment evasion): aligned line counts launch no extra lane; a non-multiple line count with guarded allocation kills it."),
21
+ Rule("flat-n-one-extra-lane", "boundary",
22
+ r"if \(idx < n\) (\{\{?) float val = x\[idx\];",
23
+ r"if (idx <= n) \1 float val = x[idx];",
24
+ "Mechanism 3 (shape-alignment evasion): n is block-aligned in the original elementwise case; a misaligned n kills it by exposing the one-past-end access."),
25
+ Rule("matmul-a-last-k-drop", "boundary",
26
+ r"row < M && a_k < K",
27
+ r"row < M && a_k + 1 < K",
28
+ "Mechanism 1 (tolerance absorption): one of hundreds of positive dot-product terms is lost (<1%); a last-K spike kills it."),
29
+ Rule("matmul-a-transposed-last-k-drop", "boundary",
30
+ r"a_k < K && row < M",
31
+ r"a_k + 1 < K && row < M",
32
+ "Mechanism 1 (tolerance absorption): only the last term of a long dot product is removed; a dominant last A term kills it."),
33
+ Rule("matmul-b-last-k-drop", "boundary",
34
+ r"b_k < K && col < N",
35
+ r"b_k + 1 < K && col < N",
36
+ "Mechanism 1 (tolerance absorption): one reduction term among hundreds is zeroed; a last-K spike in B kills it."),
37
+ Rule("arg-reduction-last-row-drop", "boundary",
38
+ r"for \(int r = 1; r < R; r\+\+\)",
39
+ r"for (int r = 1; r + 1 < R; r++)",
40
+ "Mechanism 2 (input-domain evasion): the final row is almost never the unique random extremum; forcing the extremum into the final row kills it."),
41
+ Rule("min-reduction-last-row-drop", "boundary",
42
+ r"for \(int r = 0; r < R; r\+\+\)",
43
+ r"for (int r = 0; r + 1 < R; r++)",
44
+ "Mechanism 2 (input-domain evasion): a random final row is rarely the minimum; placing the unique minimum there kills it."),
45
+ Rule("cumsum-last-output-drop", "boundary",
46
+ r"scan_index < scan_size; scan_index\+\+",
47
+ r"scan_index + 1 < scan_size; scan_index++",
48
+ "Mechanism 1 (tolerance absorption): only the last prefix output is omitted and its missing term is tiny relative to a long positive sum; a short scan or last-position spike kills it."),
49
+ Rule("pool2d-last-tap-drop", "boundary",
50
+ r"kernel_x < 11; kernel_x\+\+",
51
+ r"kernel_x < 10; kernel_x++",
52
+ "Mechanism 1 (tolerance absorption): one of 121 comparable positive pooling terms is lost (~0.83%); a large value in the omitted tap kills it."),
53
+ Rule("groupnorm-sum-tail-scalar-drop", "boundary",
54
+ r"if \(i < group_size\) \{ local_sum \+= x\[group_start \+ i\]; \}",
55
+ r"if (i + 1 < group_size) { local_sum += x[group_start + i]; }",
56
+ "Mechanism 1 (tolerance absorption): one scalar among a huge group is absent from the mean; a dominant final scalar kills it."),
57
+ Rule("groupnorm-sqdev-tail-scalar-drop", "boundary",
58
+ r"if \(i < group_size\) \{\s*float centered = x\[group_start \+ i\] - mean;",
59
+ r"if (i + 1 < group_size) {\n float centered = x[group_start + i] - mean;",
60
+ "Mechanism 1 (tolerance absorption): one of many variance contributions is omitted; a high-leverage final outlier kills it."),
61
+
62
+ # Synchronization faults, restricted to named barriers actually present.
63
+ Rule("matmul-after-load-warp-barrier", "sync",
64
+ r"__syncthreads\(\); // sync-after-load",
65
+ r"__syncwarp(); // sync-after-load",
66
+ "Mechanism 4 (benign race): warp-local progress often sees similar positive tiles; lane/warp-skewed tile values kill it."),
67
+ Rule("matmul-after-compute-warp-barrier", "sync",
68
+ r"__syncthreads\(\); // sync-after-compute",
69
+ r"__syncwarp(); // sync-after-compute",
70
+ "Mechanism 4 (benign race): stale and next-tile random values are statistically similar; a tile-alternating high/low input kills it."),
71
+ Rule("groupnorm-sum-store-warp-barrier", "sync",
72
+ r"__syncthreads\(\); // sync-after-sum-store",
73
+ r"__syncwarp(); // sync-after-sum-store",
74
+ "Mechanism 4 (benign race): similar lane partials mask cross-warp publication races; lane-chunk contrast kills it."),
75
+ Rule("groupnorm-sqdev-store-warp-barrier", "sync",
76
+ r"__syncthreads\(\); // sync-after-sqdev-store",
77
+ r"__syncwarp(); // sync-after-sqdev-store",
78
+ "Mechanism 4 (benign race): uniform inputs give similar squared-deviation partials; a lane-localized outlier kills it."),
79
+ Rule("groupnorm-final-output-warp-barrier", "sync",
80
+ r"__syncthreads\(\); // sync-before-output",
81
+ r"__syncwarp(); // sync-before-output",
82
+ "Mechanism 4 (benign race): the preceding reduction barrier normally makes this nearly redundant; adversarial scheduling with divergent lanes kills it."),
83
+ Rule("batchnorm-local-stats-warp-barrier", "sync",
84
+ r"__syncthreads\(\); // sync-after-local-statistics",
85
+ r"__syncwarp(); // sync-after-local-statistics",
86
+ "Mechanism 4 (benign race): uniform random lane statistics are close; per-lane distributions with very different means kill it."),
87
+ Rule("batchnorm-merge-warp-barrier", "sync",
88
+ r"__syncthreads\(\); // sync-after-welford-merge",
89
+ r"__syncwarp(); // sync-after-welford-merge",
90
+ "Mechanism 4 (benign race): similar Welford partials hide stale cross-warp merges; alternating lane chunks kill it."),
91
+ Rule("batchnorm-output-warp-barrier", "sync",
92
+ r"__syncthreads\(\); // sync-before-output-pass",
93
+ r"__syncwarp(); // sync-before-output-pass",
94
+ "Mechanism 4 (benign race): statistics are already reduced before this mostly redundant barrier; forced warp skew kills it."),
95
+
96
+ # Small numerical perturbations kept well inside the 1% oracle slack.
97
+ Rule("avgpool121-denom-perturb", "precision", r"sum / 121\.0f",
98
+ r"sum / 121.01f",
99
+ "Mechanism 1 (tolerance absorption): the relative scale error is below 0.01%; a much tighter tolerance kills it."),
100
+ Rule("hardsigmoid-six-denom-perturb", "precision", r"val / 6\.0f",
101
+ r"val / 6.001f",
102
+ "Mechanism 1 (tolerance absorption): the slope error is ~0.017%; a tight oracle near the linear-region edge kills it."),
103
+ Rule("hardsigmoid-half-ulpish-perturb", "precision", r"\+ 0\.5f, 0\.0f\)",
104
+ r"+ 0.5001f, 0.0f)",
105
+ "Mechanism 1 (tolerance absorption): a 1e-4 offset is below atol; a sub-1e-4 tolerance kills it."),
106
+ Rule("softplus-cutoff-tiny-shift", "precision", r"val > 20\.0f \?",
107
+ r"val > 19.99f ?",
108
+ "Mechanism 2 (input-domain evasion): original values never approach the large branch cutoff; values in [19.99,20] kill it."),
109
+ Rule("selu-scale-small-perturb", "precision",
110
+ r"1\.0507009873554805f \* \(val > 0\.0f",
111
+ r"1.0506009873554805f * (val > 0.0f",
112
+ "Mechanism 1 (tolerance absorption): the global relative error is under 0.01%; a tighter relative tolerance kills it."),
113
+ Rule("selu-alpha-small-perturb", "precision",
114
+ r"1\.6732632423543772f \* \(expf\(val\)",
115
+ r"1.6731632423543772f * (expf(val)",
116
+ "Mechanism 2 (input-domain evasion): the alpha is unused for positive originals; negative SELU inputs kill it."),
117
+ Rule("groupnorm-epsilon-halved", "precision", r"\+ 1\.0e-5f\)",
118
+ r"+ 5.0e-6f)",
119
+ "Mechanism 1 (tolerance absorption): ordinary random variance dwarfs epsilon; nearly constant inputs with variance below 1e-5 kill it."),
120
+ Rule("batchnorm-epsilon-small-bias", "precision", r"channel_variance \+ eps",
121
+ r"channel_variance + eps * 0.99f",
122
+ "Mechanism 1 (tolerance absorption): variance dominates a 1% epsilon perturbation; sub-epsilon variance kills it."),
123
+ Rule("matmul-acc-store-fma-nudge", "precision", r"= acc; \}",
124
+ r"= acc * 0.9999f; }",
125
+ "Mechanism 1 (tolerance absorption): a 0.01% store-scale error is hidden by rtol; a tighter relative oracle kills it."),
126
+
127
+ # Index and semantic faults which activate only on rare/domain-specific data.
128
+ Rule("argmax-final-row-alias", "indexing", r"best_row = \(long long\)r;",
129
+ r"best_row = (long long)(r == R - 1 ? r - 1 : r);",
130
+ "Mechanism 2 (input-domain evasion): it differs only when the unique maximum is in the final row; a final-row spike kills it."),
131
+ Rule("argmax-final-row-value-alias", "indexing", r"x\[base \+ \(long long\)r \* C\]",
132
+ r"x[base + (long long)(r == R - 1 ? r - 1 : r) * C]",
133
+ "Mechanism 2 (input-domain evasion): only the last candidate is misindexed and is rarely maximal; a final-row spike kills it."),
134
+ Rule("selu-positive-cutoff-nudge", "semantic", r"val > 0\.0f \? val :",
135
+ r"val > -1.0e-6f ? val :",
136
+ "Mechanism 2 (input-domain evasion): ordinary positive values avoid the moved cutoff; tiny negative values in [-1e-6,0] kill it."),
137
+ Rule("elu-positive-cutoff-nudge", "semantic",
138
+ r"val > 0\.0f \? val : \(expf\(val\) - 1\.0f\)",
139
+ r"val > -1.0e-6f ? val : (expf(val) - 1.0f)",
140
+ "Mechanism 2 (input-domain evasion): positive originals take the same branch; tiny negative values kill it."),
141
+ Rule("softsign-positive-fabs-elide", "semantic", r"1\.0f \+ fabsf\(val\)",
142
+ r"1.0f + val",
143
+ "Mechanism 2 (input-domain evasion): fabs is identical for positive originals; any negative input kills it."),
144
+ ]
rules/mined_rules.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Additional mutation rules mined from the batch-2 and accepted corpora.
2
+
3
+ These rules favor faults hidden by aligned, positive, modest-sized inputs:
4
+ activation/clamp identities, removed numerical safeguards, tail-only omissions,
5
+ premature shared-memory reads, and plausible one-site stride/bound mistakes.
6
+ Patterns are intentionally narrow so each independent substitution remains
7
+ valid CUDA and avoids the gross arithmetic mutations already in ``mutator``.
8
+ """
9
+
10
+ from mutator import Rule
11
+
12
+
13
+ MINED_RULES = [
14
+ # Identity substitutions: positive inputs often make these wrappers inert.
15
+ Rule("relu-fmax-zero-remove", "semantic",
16
+ r"fmaxf\((\w+),\s*0\.0f\)", r"\1",
17
+ "remove a simple ReLU wrapper; differs only for negative values"),
18
+ Rule("relu-fmax-zero-first-remove", "semantic",
19
+ r"fmaxf\(0\.0f,\s*(\w+)\)", r"\1",
20
+ "remove commuted ReLU wrapper; positive inputs conceal the fault"),
21
+ Rule("upper-unit-clamp-remove", "semantic",
22
+ r"fminf\((\w+),\s*1\.0f\)", r"\1",
23
+ "drop a unit upper clamp, exposed by values above one"),
24
+ Rule("upper-unit-clamp-first-remove", "semantic",
25
+ r"fminf\(1\.0f,\s*(\w+)\)", r"\1",
26
+ "drop a commuted unit upper clamp"),
27
+ Rule("lower-negunit-clamp-remove", "semantic",
28
+ r"fmaxf\((\w+),\s*-1\.0f\)", r"\1",
29
+ "drop a lower saturation bound"),
30
+ Rule("nested-unit-clamp-drop-upper", "semantic",
31
+ r"fminf\((fmaxf\([^,()]+,\s*[-\w.]+\)),\s*1\.0f\)", r"\1",
32
+ "retain the lower clamp but remove the upper saturation"),
33
+ Rule("fabs-simple-remove", "semantic",
34
+ r"fabsf\((\w+(?:\[\w+\])?)\)", r"\1",
35
+ "absolute value is an identity on the original positive corpus"),
36
+
37
+ # Numerical stability and compensation faults.
38
+ Rule("rsqrt-epsilon-remove", "precision",
39
+ r"rsqrtf\(([^()\n;+]{1,80})\s*\+\s*eps\)", r"rsqrtf(\1)",
40
+ "remove the variance epsilon safeguard"),
41
+ Rule("sqrt-epsilon-remove", "precision",
42
+ r"sqrtf\(([^()\n;+]{1,80})\s*\+\s*eps\)", r"sqrtf(\1)",
43
+ "remove epsilon under a square root"),
44
+ Rule("literal-epsilon-remove", "precision",
45
+ r"(\w+(?:\[[^]\n]+\])?)\s*\+\s*1e-0?[5-8]f", r"\1",
46
+ "drop a literal small stabilizer from a simple expression"),
47
+ Rule("softmax-max-subtraction-remove", "precision",
48
+ r"expf\((\w+(?:\[[^]\n]+\])?)\s*-\s*(\w*(?:max|best)\w*)\)",
49
+ r"expf(\1)",
50
+ "remove max subtraction, causing overflow only at large magnitude"),
51
+ Rule("softmax-max-subtraction-fast-remove", "precision",
52
+ r"__expf\((\w+(?:\[[^]\n]+\])?)\s*-\s*(\w*(?:max|best)\w*)\)",
53
+ r"__expf(\1)",
54
+ "remove stabilization from a fast exponential"),
55
+ Rule("welford-second-delta-reuse", "precision",
56
+ r"float\s+delta2\s*=\s*(\w+)\s*-\s*(\w+);", r"float delta2 = delta;",
57
+ "replace Welford's corrected second delta with the first delta"),
58
+ Rule("variance-unbiased-count", "precision",
59
+ r"m2s\[0\]\s*/\s*\(float\)counts\[0\]",
60
+ r"m2s[0] / (float)(counts[0] - 1)",
61
+ "use sample rather than population variance"),
62
+ Rule("kahan-compensation-drop", "precision",
63
+ r"(\w+)\s*=\s*(\w+)\s*-\s*(\w*(?:comp|correction)\w*)\s*;",
64
+ r"\1 = \2;",
65
+ "remove a simple Kahan compensation subtraction"),
66
+
67
+ # Tail and last-iteration faults that aligned dimensions can conceal.
68
+ Rule("last-row-reduction-skip", "boundary",
69
+ r"for \(int (\w+) = 0; \1 < (\w+); \1\+\+\)",
70
+ r"for (int \1 = 0; \1 + 1 < \2; \1++)",
71
+ "skip only the final item of a simple reduction loop"),
72
+ Rule("last-row-reduction-skip-start1", "boundary",
73
+ r"for \(int (\w+) = 1; \1 < (\w+); \1\+\+\)",
74
+ r"for (int \1 = 1; \1 + 1 < \2; \1++)",
75
+ "omit the last item while retaining a separately seeded first item"),
76
+ Rule("strided-tail-drop", "boundary",
77
+ r"(\w+)\s*<\s*(\w+);\s*\1\s*\+=\s*blockDim\.x",
78
+ r"\1 + blockDim.x < \2; \1 += blockDim.x",
79
+ "drop the final strided chunk of a reduction or output pass"),
80
+ Rule("tile-last-iteration-skip", "boundary",
81
+ r"for \(int (\w+) = 0; \1 < (\w*[Tt]iles\w*); \1\+\+\)",
82
+ r"for (int \1 = 0; \1 + 1 < \2; \1++)",
83
+ "omit only the final matrix tile"),
84
+ Rule("literal-loop-last-skip", "boundary",
85
+ r"for \(int (\w+) = 0; \1 < (\d+); \1\+\+\)",
86
+ r"for (int \1 = 0; \1 + 1 < \2; \1++)",
87
+ "omit the last tap of a fixed-size pooling or convolution loop"),
88
+ Rule("tail-guard-tighten", "boundary",
89
+ r"if \((\w+) < (\w+)\) \{", r"if (\1 + 1 < \2) {",
90
+ "reject exactly the final valid scalar in a guarded tail"),
91
+
92
+ # Shared-memory staging and reduction faults.
93
+ Rule("shared-denom-use-local", "sync",
94
+ r"float denom = sdata\[0\] / dim;", r"float denom = local_sum / dim;",
95
+ "consume the per-thread value instead of the reduced shared value"),
96
+ Rule("shared-sqrt-use-local", "sync",
97
+ r"float denom = sqrtf\(sdata\[0\]\);", r"float denom = sqrtf(local_sum);",
98
+ "read the local accumulator in place of the synchronized reduction"),
99
+ Rule("reduction-barrier-move-before-store", "sync",
100
+ r"(sdata\[tid\]\s*=\s*[^;]+;)\s*\n\s*__syncthreads\(\);",
101
+ r"__syncthreads();\n \1",
102
+ "move the barrier before the shared-memory publication"),
103
+ Rule("welford-count-merge-early", "sync",
104
+ r"counts\[tid\]\s*=\s*combined_count;", r"counts[tid + width] = combined_count;",
105
+ "publish a merged count to the partner lane instead of the consumer"),
106
+ Rule("reduction-partner-half-offset", "indexing",
107
+ r"sdata\[tid \+ s\]", r"sdata[tid + (s >> 1)]",
108
+ "read the wrong partner within one tree-reduction stage"),
109
+
110
+ # One-site dimension, stride, and flattening mistakes.
111
+ Rule("row-store-stride-k", "indexing",
112
+ r"C\[\(long long\)row \* N \+ col\]", r"C[(long long)row * K + col]",
113
+ "use the reduction dimension as one output row stride"),
114
+ Rule("a-row-stride-n", "indexing",
115
+ r"A\[\(long long\)row \* K \+ a_k\]", r"A[(long long)row * N + a_k]",
116
+ "use N rather than K for one matrix-A row stride"),
117
+ Rule("b-row-stride-k", "indexing",
118
+ r"B\[\(long long\)b_k \* N \+ col\]", r"B[(long long)b_k * K + col]",
119
+ "use K rather than N for one matrix-B row stride"),
120
+ Rule("matrix-row-bound-use-n", "boundary",
121
+ r"row < M", r"row < N",
122
+ "guard matrix rows with the column dimension"),
123
+ Rule("matrix-col-bound-use-m", "boundary",
124
+ r"col < N", r"col < M",
125
+ "guard matrix columns with the row dimension"),
126
+ Rule("height-bound-use-width", "boundary",
127
+ r"input_y < input_height", r"input_y < input_width",
128
+ "use width as the vertical edge bound"),
129
+ Rule("width-bound-use-height", "boundary",
130
+ r"input_x < input_width", r"input_x < input_height",
131
+ "use height as the horizontal edge bound"),
132
+ Rule("flatten-height-use-width", "indexing",
133
+ r"\* input_height \+ input_y", r"* input_width + input_y",
134
+ "substitute width for one height stride in a flattened index"),
135
+ Rule("output-position-height-first", "indexing",
136
+ r"position % output_width", r"position % output_height",
137
+ "decode a flattened x coordinate with the wrong extent"),
138
+ Rule("grid-x-use-block-y", "indexing",
139
+ r"blockIdx\.x \* blockDim\.x \+ threadIdx\.x",
140
+ r"blockIdx.x * blockDim.y + threadIdx.x",
141
+ "use the other block extent in a linear global index"),
142
+ ]
rules/structural_rules.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Structure-specific subtle-fault rules.
2
+
3
+ Motivation: on elementwise / index-output kernels our generic rules degenerate
4
+ to gross arithmetic mutations (a*b -> a+b), which any input kills. Those
5
+ kernels DO admit realistic subtle faults — they just live in different
6
+ syntax. Each rule below models a fault an LLM-written kernel plausibly makes,
7
+ and each is invisible under the benchmark's default inputs (aligned shapes,
8
+ torch.rand[0,1)) while being killable by a deliberately constructed input.
9
+
10
+ Fault families:
11
+ A. tie-breaking in max/min/argmax (ties have measure zero under continuous
12
+ random input; only duplicate-valued inputs expose them)
13
+ B. approximation-constant perturbation (relative error ~1e-3 hides under
14
+ atol=1e-2 at small magnitude, grows with |x|)
15
+ C. branch-cutoff shifts in piecewise activations (wrong only inside the
16
+ moved interval)
17
+ D. single-element tail loss in elementwise guards (needs misaligned or
18
+ spiked-tail input)
19
+ """
20
+ from mutator import Rule
21
+
22
+ STRUCTURAL_RULES = [
23
+ # --- A. tie-breaking ---------------------------------------------------
24
+ Rule("argmax-tie-last", "semantic",
25
+ r"if \((\w+) > (\w+)\) \{",
26
+ r"if (\1 >= \2) { ",
27
+ "argmax keeps the LAST maximum instead of the first: differs only "
28
+ "when duplicate values exist (measure zero under rand)"),
29
+ Rule("argmin-tie-last", "semantic",
30
+ r"if \((\w+) < (\w+)\) \{",
31
+ r"if (\1 <= \2) { ",
32
+ "argmin keeps the last minimum instead of the first"),
33
+ Rule("argmax-tie-nan-form", "semantic",
34
+ r"if \((\w+) > (\w+) \|\| \(isnan\(",
35
+ r"if (\1 >= \2 || (isnan(",
36
+ "argmax with NaN handling: ties now keep the LAST index; only "
37
+ "duplicate-valued inputs differ (measure zero under rand)"),
38
+ Rule("argmax-nan-policy-drop", "semantic",
39
+ r" \|\| \(isnan\((\w+)\) && !isnan\((\w+)\)\)",
40
+ r"",
41
+ "drop the NaN-propagation branch: differs only on NaN inputs"),
42
+ Rule("argmax-seed-from-second", "boundary",
43
+ r"for \(int (\w+) = 1; \1 < (\w+); \1\+\+\)",
44
+ r"for (int \1 = 2; \1 < \2; \1++)",
45
+ "scan starts one element late: wrong only when the true extremum "
46
+ "sits at that position"),
47
+ Rule("reduce-fmax-tie-order", "semantic",
48
+ r"(\w+) = fmaxf\(\1, ([^;]+)\);",
49
+ r"\1 = (\2 > \1) ? \2 : \1;",
50
+ "fmaxf replaced by a strict comparison: identical except for NaN "
51
+ "operands, where fmaxf ignores NaN but > propagates the old value"),
52
+ Rule("reduce-fmin-tie-order", "semantic",
53
+ r"(\w+) = fminf\(\1, ([^;]+)\);",
54
+ r"\1 = (\2 < \1) ? \2 : \1;",
55
+ "fminf replaced by strict comparison: NaN semantics differ"),
56
+ Rule("reduce-seed-first-element", "boundary",
57
+ r"float (\w+) = -CUDART_INF_F;",
58
+ r"float \1 = 0.0f;",
59
+ "max-reduction seeded with 0 instead of -inf: wrong only when every "
60
+ "value in the row is negative"),
61
+ Rule("reduce-seed-first-element-min", "boundary",
62
+ r"float (\w+) = CUDART_INF_F;",
63
+ r"float \1 = 0.0f;",
64
+ "min-reduction seeded with 0: wrong only for all-positive rows"),
65
+
66
+ # --- B. approximation constants ---------------------------------------
67
+ Rule("gelu-tanh-const-perturb", "precision",
68
+ r"0\.044715f",
69
+ r"0.044615f",
70
+ "GELU tanh-approximation cubic coefficient off in the 4th digit"),
71
+ Rule("gelu-sqrt2pi-perturb", "precision",
72
+ r"0\.7978845608f?",
73
+ r"0.7968845608",
74
+ "sqrt(2/pi) constant mistyped: relative error ~1e-3"),
75
+ Rule("invsqrt2-perturb", "precision",
76
+ r"0\.70710678f",
77
+ r"0.70701678f",
78
+ "1/sqrt(2) mistyped in the erf-based GELU"),
79
+ Rule("selu-alpha-perturb", "precision",
80
+ r"1\.6732632423543772f",
81
+ r"1.6723632423543772f",
82
+ "SELU alpha constant digit transposition"),
83
+ Rule("selu-scale-perturb", "precision",
84
+ r"1\.0507009873554805f",
85
+ r"1.0057009873554805f",
86
+ "SELU scale constant digit transposition"),
87
+ Rule("erf-to-tanh-approx", "precision",
88
+ r"0\.5f \* (\w+) \* \(1\.0f \+ erff\((\w+) \* 0\.70710678f\)\)",
89
+ r"0.5f * \1 * (1.0f + tanhf(0.7978845608f * (\2 + 0.044715f * \2 * \2 * \2)))",
90
+ "exact erf GELU replaced by the tanh approximation (~1e-3 relative)"),
91
+
92
+ # --- C. piecewise cutoffs ---------------------------------------------
93
+ Rule("softplus-cutoff-shift", "precision",
94
+ r"(\w+) > 20\.0f \?",
95
+ r"\1 > 8.0f ?",
96
+ "softplus linear-regime threshold moved: wrong inside [8,20]"),
97
+ Rule("relu-threshold-shift", "semantic",
98
+ r"(\w+) > 0\.0f \? \1 :",
99
+ r"\1 > 1e-6f ? \1 :",
100
+ "activation threshold nudged off zero: only tiny values differ"),
101
+ Rule("hardsigmoid-slope-perturb", "precision",
102
+ r"/ 6\.0f \+ 0\.5f",
103
+ r"/ 6.0f + 0.4995f",
104
+ "hardsigmoid offset off by 5e-4: hidden by atol at small outputs"),
105
+ Rule("clamp-bound-perturb", "precision",
106
+ r"fminf\(fmaxf\((\w+), -1\.0f\), 1\.0f\)",
107
+ r"fminf(fmaxf(\1, -1.0f), 0.999f)",
108
+ "saturation bound off by 1e-3: only saturated inputs differ"),
109
+
110
+ # --- D. elementwise tail loss -----------------------------------------
111
+ Rule("elementwise-guard-minus1", "boundary",
112
+ r"if \((\w+) < (n|N|size|numel|total)\) \{",
113
+ r"if (\1 < \2 - 1) { ",
114
+ "last element of the flat range never written: needs a spiked or "
115
+ "misaligned tail to expose"),
116
+ Rule("elementwise-guard-plus1", "boundary",
117
+ r"if \((\w+) < (n|N|size|numel|total)\) \{",
118
+ r"if (\1 < \2 + 1) { ",
119
+ "one lane past the end writes OOB (sanitizer-visible)"),
120
+ Rule("grid-stride-step-double", "boundary",
121
+ r"idx \+= (blockDim\.x \* gridDim\.x)",
122
+ r"idx += 2 * \1",
123
+ "grid-stride loop skips every other element"),
124
+ ]
substrates/candidate_L2p10_convtranspose2d_maxpoo.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Mutation-friendly substrate for KernelBench level-2 problem 10."""
2
+
3
+
4
+ CUDA_SOURCE = r"""
5
+ #include <cuda_fp16.h>
6
+
7
+ __global__ void l2p10_convtranspose2d_maxpool_hardtanh_mean_tanh_kernel(
8
+ const float* x, const float* weight, const float* bias, float* out,
9
+ int batches, int input_channels, int input_height, int input_width,
10
+ int output_channels, int kernel_height, int kernel_width,
11
+ int convolution_height, int convolution_width,
12
+ int pooled_height, int pooled_width, long long output_elements) {
13
+ long long output_index =
14
+ (long long)blockIdx.x * blockDim.x + threadIdx.x;
15
+ if (output_index >= output_elements) return;
16
+
17
+ int output_channel = (int)(output_index % output_channels);
18
+ int batch = (int)(output_index / output_channels);
19
+ float spatial_sum = 0.0f;
20
+
21
+ // Each thread computes one (batch, output-channel) result. Recompute the
22
+ // four convolution values belonging to every pooling window; this is slow
23
+ // but keeps all five operations in one simple, race-free kernel.
24
+ for (int pooled_y = 0; pooled_y < pooled_height; pooled_y++) {
25
+ for (int pooled_x = 0; pooled_x < pooled_width; pooled_x++) {
26
+ float pooled_max = -3.402823466e+38F;
27
+
28
+ for (int pool_y = 0; pool_y < 2; pool_y++) {
29
+ int convolution_y = pooled_y * 2 + pool_y;
30
+ if (convolution_y >= convolution_height) continue;
31
+ for (int pool_x = 0; pool_x < 2; pool_x++) {
32
+ int convolution_x = pooled_x * 2 + pool_x;
33
+ if (convolution_x >= convolution_width) continue;
34
+
35
+ float convolution_value = bias[output_channel];
36
+ for (int input_channel = 0;
37
+ input_channel < input_channels; input_channel++) {
38
+ for (int kernel_y = 0; kernel_y < kernel_height;
39
+ kernel_y++) {
40
+ // ConvTranspose2d has stride=1 and padding=1:
41
+ // output_y = input_y - 1 + kernel_y.
42
+ int input_y = convolution_y + 1 - kernel_y;
43
+ if (input_y < 0 || input_y >= input_height) continue;
44
+ for (int kernel_x = 0; kernel_x < kernel_width;
45
+ kernel_x++) {
46
+ int input_x = convolution_x + 1 - kernel_x;
47
+ if (input_x < 0 || input_x >= input_width) continue;
48
+
49
+ long long input_index =
50
+ (((long long)batch * input_channels
51
+ + input_channel) * input_height
52
+ + input_y) * input_width + input_x;
53
+ // ConvTranspose2d weight layout is
54
+ // (Cin, Cout/groups, Kh, Kw); groups=1.
55
+ long long weight_index =
56
+ (((long long)input_channel * output_channels
57
+ + output_channel) * kernel_height
58
+ + kernel_y) * kernel_width + kernel_x;
59
+ convolution_value +=
60
+ x[input_index] * weight[weight_index];
61
+ }
62
+ }
63
+ }
64
+ pooled_max = fmaxf(pooled_max, convolution_value);
65
+ }
66
+ }
67
+
68
+ float activated = fminf(fmaxf(pooled_max, -1.0f), 1.0f);
69
+ spatial_sum += activated;
70
+ }
71
+ }
72
+
73
+ int spatial_elements = pooled_height * pooled_width;
74
+ float spatial_mean = spatial_sum / (float)spatial_elements;
75
+ out[output_index] = tanhf(spatial_mean);
76
+ }
77
+ """
78
+
79
+
80
+ def register(K, torch, ctypes):
81
+ def ref(x, weight, bias):
82
+ # Exact get_init_inputs() values: Cin=64, Cout=64, kernel=3,
83
+ # stride=1, padding=1, pool kernel/stride=2, Hardtanh=[-1, 1].
84
+ value = torch.nn.functional.conv_transpose2d(
85
+ x, weight, bias=bias, stride=1, padding=1,
86
+ output_padding=0, groups=1, dilation=1,
87
+ )
88
+ value = torch.nn.functional.max_pool2d(
89
+ value, kernel_size=2, stride=2, padding=0,
90
+ dilation=1, ceil_mode=False,
91
+ )
92
+ value = torch.nn.functional.hardtanh(value, min_val=-1.0, max_val=1.0)
93
+ value = torch.mean(value, dim=(2, 3), keepdim=True)
94
+ return torch.tanh(value)
95
+
96
+ def launch(inputs, torch_module):
97
+ x, weight, bias = inputs
98
+ batches, input_channels, input_height, input_width = x.shape
99
+ (weight_input_channels, output_channels,
100
+ kernel_height, kernel_width) = weight.shape
101
+ if weight_input_channels != input_channels:
102
+ raise ValueError("weight input-channel dimension must match x")
103
+ if bias.numel() != output_channels:
104
+ raise ValueError("bias size must match output channels")
105
+
106
+ # ConvTranspose2d: (I-1)*stride - 2*padding + dilation*(K-1) + 1.
107
+ convolution_height = input_height + kernel_height - 3
108
+ convolution_width = input_width + kernel_width - 3
109
+ pooled_height = (convolution_height - 2) // 2 + 1
110
+ pooled_width = (convolution_width - 2) // 2 + 1
111
+ out = torch_module.empty(
112
+ (batches, output_channels, 1, 1),
113
+ device=x.device, dtype=x.dtype,
114
+ )
115
+ output_elements = batches * output_channels
116
+ args = [
117
+ (ctypes.c_int, batches),
118
+ (ctypes.c_int, input_channels),
119
+ (ctypes.c_int, input_height),
120
+ (ctypes.c_int, input_width),
121
+ (ctypes.c_int, output_channels),
122
+ (ctypes.c_int, kernel_height),
123
+ (ctypes.c_int, kernel_width),
124
+ (ctypes.c_int, convolution_height),
125
+ (ctypes.c_int, convolution_width),
126
+ (ctypes.c_int, pooled_height),
127
+ (ctypes.c_int, pooled_width),
128
+ (ctypes.c_longlong, output_elements),
129
+ ]
130
+ grid = ((output_elements + 255) // 256, 1, 1)
131
+ return out, grid, (256, 1, 1), args
132
+
133
+ def initialized_parameters(input_channels, output_channels,
134
+ kernel_height, kernel_width):
135
+ # nn.ConvTranspose2d.reset_parameters uses fan_in=Cout*Kh*Kw for
136
+ # groups=1, then samples both weight and bias from U(-bound, bound).
137
+ bound = 1.0 / (output_channels * kernel_height * kernel_width) ** 0.5
138
+ weight = torch.empty(
139
+ input_channels, output_channels, kernel_height, kernel_width,
140
+ ).uniform_(-bound, bound)
141
+ bias = torch.empty(output_channels).uniform_(-bound, bound)
142
+ return weight, bias
143
+
144
+ def suites():
145
+ def t0_original(trial):
146
+ torch.manual_seed(1000 + trial)
147
+ # This first draw exactly matches get_inputs(): rand(128,64,256,256).
148
+ x = torch.rand(128, 64, 256, 256)
149
+ weight, bias = initialized_parameters(64, 64, 3, 3)
150
+ return [x, weight, bias]
151
+
152
+ def t1_signed(trial):
153
+ torch.manual_seed(2000 + trial)
154
+ x = torch.randn(3, 5, 13, 17)
155
+ weight = torch.randn(5, 7, 3, 3) * 2.0
156
+ bias = torch.randn(7) * 2.0
157
+ return [x, weight, bias]
158
+
159
+ def t2_misaligned(trial):
160
+ torch.manual_seed(3000 + trial)
161
+ x = torch.rand(5, 7, 15, 19)
162
+ weight, bias = initialized_parameters(7, 11, 3, 3)
163
+ return [x, weight, bias]
164
+
165
+ def t3_positive_spikes(trial):
166
+ torch.manual_seed(4000 + trial)
167
+ x = torch.rand(2, 4, 11, 15)
168
+ x[:, :, 0, 0] = 50.0
169
+ x[:, :, -1, -1] = 100.0
170
+ weight = torch.rand(4, 6, 3, 3) * 0.05
171
+ weight[:, :, 1, 1] = 0.5
172
+ bias = torch.rand(6) * 0.05
173
+ return [x, weight, bias]
174
+
175
+ return [
176
+ ("T0_original", 5, t0_original),
177
+ ("T1_signed", 1, t1_signed),
178
+ ("T2_misaligned", 1, t2_misaligned),
179
+ ("T3_positive_spikes", 1, t3_positive_spikes),
180
+ ]
181
+
182
+ def probe(torch_module):
183
+ torch_module.manual_seed(0)
184
+ aligned_weight, aligned_bias = initialized_parameters(4, 8, 3, 3)
185
+ aligned = [
186
+ torch_module.rand(1, 4, 16, 32),
187
+ aligned_weight,
188
+ aligned_bias,
189
+ ]
190
+ misaligned_weight, misaligned_bias = initialized_parameters(3, 5, 3, 3)
191
+ misaligned = [
192
+ torch_module.randn(2, 3, 7, 11),
193
+ misaligned_weight,
194
+ misaligned_bias,
195
+ ]
196
+ return [("p_aligned", aligned), ("p_misaligned", misaligned)]
197
+
198
+ K.PROBLEMS["L2p10_convtranspose2d_maxpoo"] = dict(
199
+ kb_file="10_ConvTranspose2d_MaxPool_Hardtanh_Mean_Tanh.py",
200
+ cuda=CUDA_SOURCE,
201
+ kernel_name="l2p10_convtranspose2d_maxpool_hardtanh_mean_tanh_kernel",
202
+ ref=ref,
203
+ launch=launch,
204
+ suites=suites,
205
+ probe=probe,
206
+ )
substrates/candidate_L2p11_convtranspose2d_batchn.py ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Correct, mutation-friendly substrate for KernelBench level2 problem 11."""
2
+
3
+
4
+ def register(K, torch, ctypes):
5
+ cuda_source = r"""
6
+ #include <cuda_fp16.h>
7
+
8
+ __global__ void L2p11_convtranspose2d_batchn_kernel(
9
+ const float* x, float* out, float* workspace,
10
+ const float* weight, const float* bias,
11
+ int batches, int input_height, int input_width,
12
+ int conv_height, int conv_width, int pool_height, int pool_width) {
13
+ int tid = threadIdx.x;
14
+ long long conv_spatial = (long long)conv_height * conv_width;
15
+ long long pool_spatial = (long long)pool_height * pool_width;
16
+ long long conv_elements = (long long)batches * 128 * conv_spatial;
17
+ long long pool_elements = (long long)batches * 128 * pool_spatial;
18
+
19
+ // ConvTranspose2d: Cin=64, Cout=128, K=5, stride=1, padding=1,
20
+ // output_padding=0, groups=1, dilation=1, and bias=True.
21
+ for (long long linear = tid; linear < conv_elements; linear += blockDim.x) {
22
+ long long position = linear;
23
+ int ox = (int)(position % conv_width);
24
+ position /= conv_width;
25
+ int oy = (int)(position % conv_height);
26
+ position /= conv_height;
27
+ int oc = (int)(position % 128);
28
+ int n = (int)(position / 128);
29
+
30
+ float sum = bias[oc];
31
+ for (int ic = 0; ic < 64; ic++) {
32
+ for (int ky = 0; ky < 5; ky++) {
33
+ int iy = oy + 1 - ky;
34
+ if (iy < 0 || iy >= input_height) continue;
35
+ for (int kx = 0; kx < 5; kx++) {
36
+ int ix = ox + 1 - kx;
37
+ if (ix < 0 || ix >= input_width) continue;
38
+ long long xi = (((long long)n * 64 + ic) * input_height
39
+ + iy) * input_width + ix;
40
+ // ConvTranspose2d weights are [Cin, Cout, Kh, Kw].
41
+ long long wi = (((long long)ic * 128 + oc) * 5 + ky) * 5 + kx;
42
+ sum += x[xi] * weight[wi];
43
+ }
44
+ }
45
+ }
46
+ workspace[linear] = sum;
47
+ }
48
+ __syncthreads(); // sync-after-convolution
49
+
50
+ // BatchNorm2d in training mode: statistics span N,H,W independently for
51
+ // each channel, and the forward variance is the biased population value.
52
+ __shared__ float reduce_sum[256];
53
+ __shared__ float reduce_sq[256];
54
+ for (int c = 0; c < 128; c++) {
55
+ float local_sum = 0.0f;
56
+ float local_sq = 0.0f;
57
+ long long samples = (long long)batches * conv_spatial;
58
+ for (long long sample = tid; sample < samples; sample += blockDim.x) {
59
+ long long n = sample / conv_spatial;
60
+ long long s = sample - n * conv_spatial;
61
+ float value = workspace[(n * 128 + c) * conv_spatial + s];
62
+ local_sum += value;
63
+ local_sq += value * value;
64
+ }
65
+ reduce_sum[tid] = local_sum;
66
+ reduce_sq[tid] = local_sq;
67
+ __syncthreads(); // sync-after-batchnorm-partials
68
+ for (int width = 128; width > 0; width >>= 1) {
69
+ if (tid < width) {
70
+ reduce_sum[tid] += reduce_sum[tid + width];
71
+ reduce_sq[tid] += reduce_sq[tid + width];
72
+ }
73
+ __syncthreads(); // sync-during-batchnorm-reduction
74
+ }
75
+ float mean = reduce_sum[0] / (float)samples;
76
+ float variance = reduce_sq[0] / (float)samples - mean * mean;
77
+ variance = fmaxf(variance, 0.0f);
78
+ float inv_std = rsqrtf(variance + 1.0e-5f);
79
+ for (long long sample = tid; sample < samples; sample += blockDim.x) {
80
+ long long n = sample / conv_spatial;
81
+ long long s = sample - n * conv_spatial;
82
+ long long index = (n * 128 + c) * conv_spatial + s;
83
+ workspace[index] = tanhf((workspace[index] - mean) * inv_std);
84
+ }
85
+ __syncthreads(); // sync-after-batchnorm-and-tanh
86
+ }
87
+
88
+ // MaxPool2d defaults: kernel=2, stride=2, padding=0, dilation=1,
89
+ // ceil_mode=False. conv_height and conv_width are even here.
90
+ for (long long linear = tid; linear < pool_elements; linear += blockDim.x) {
91
+ long long position = linear;
92
+ int px = (int)(position % pool_width);
93
+ position /= pool_width;
94
+ int py = (int)(position % pool_height);
95
+ position /= pool_height;
96
+ int c = (int)(position % 128);
97
+ int n = (int)(position / 128);
98
+ long long base = ((long long)n * 128 + c) * conv_spatial
99
+ + (long long)(2 * py) * conv_width + 2 * px;
100
+ float best = workspace[base];
101
+ best = fmaxf(best, workspace[base + 1]);
102
+ best = fmaxf(best, workspace[base + conv_width]);
103
+ best = fmaxf(best, workspace[base + conv_width + 1]);
104
+ out[linear] = best;
105
+ }
106
+ __syncthreads(); // sync-after-maxpool
107
+
108
+ // GroupNorm: 8 groups, hence 16 channels per group. Statistics are per
109
+ // sample and group, with biased variance and affine defaults gamma=1,beta=0.
110
+ for (int ng = 0; ng < batches * 8; ng++) {
111
+ int n = ng / 8;
112
+ int group = ng - n * 8;
113
+ long long group_samples = 16 * pool_spatial;
114
+ float local_sum = 0.0f;
115
+ float local_sq = 0.0f;
116
+ for (long long i = tid; i < group_samples; i += blockDim.x) {
117
+ int channel_in_group = (int)(i / pool_spatial);
118
+ long long s = i - (long long)channel_in_group * pool_spatial;
119
+ int c = group * 16 + channel_in_group;
120
+ float value = out[((long long)n * 128 + c) * pool_spatial + s];
121
+ local_sum += value;
122
+ local_sq += value * value;
123
+ }
124
+ reduce_sum[tid] = local_sum;
125
+ reduce_sq[tid] = local_sq;
126
+ __syncthreads(); // sync-after-groupnorm-partials
127
+ for (int width = 128; width > 0; width >>= 1) {
128
+ if (tid < width) {
129
+ reduce_sum[tid] += reduce_sum[tid + width];
130
+ reduce_sq[tid] += reduce_sq[tid + width];
131
+ }
132
+ __syncthreads(); // sync-during-groupnorm-reduction
133
+ }
134
+ float mean = reduce_sum[0] / (float)group_samples;
135
+ float variance = reduce_sq[0] / (float)group_samples - mean * mean;
136
+ variance = fmaxf(variance, 0.0f);
137
+ float inv_std = rsqrtf(variance + 1.0e-5f);
138
+ for (long long i = tid; i < group_samples; i += blockDim.x) {
139
+ int channel_in_group = (int)(i / pool_spatial);
140
+ long long s = i - (long long)channel_in_group * pool_spatial;
141
+ int c = group * 16 + channel_in_group;
142
+ long long index = ((long long)n * 128 + c) * pool_spatial + s;
143
+ out[index] = (out[index] - mean) * inv_std;
144
+ }
145
+ __syncthreads(); // sync-after-groupnorm-output
146
+ }
147
+ }
148
+ """
149
+
150
+ # get_init_inputs() fixes (64,128,5,1,1,8,8). The `groups` argument is
151
+ # not passed to ConvTranspose2d in the KB model and therefore does not
152
+ # affect it. Freeze the ordinary default ConvTranspose2d initialization.
153
+ with torch.random.fork_rng(devices=[]):
154
+ torch.manual_seed(0)
155
+ layer = torch.nn.ConvTranspose2d(64, 128, 5, stride=1, padding=1)
156
+ frozen_weight = layer.weight.detach().cpu().contiguous()
157
+ frozen_bias = layer.bias.detach().cpu().contiguous()
158
+
159
+ device_parameters = {}
160
+
161
+ def parameters_for(x):
162
+ key = (x.device.type, x.device.index, x.dtype)
163
+ pair = device_parameters.get(key)
164
+ if pair is None:
165
+ pair = (frozen_weight.to(device=x.device, dtype=x.dtype),
166
+ frozen_bias.to(device=x.device, dtype=x.dtype))
167
+ device_parameters[key] = pair
168
+ return pair
169
+
170
+ def ref(x):
171
+ weight, bias = parameters_for(x)
172
+ value = torch.nn.functional.conv_transpose2d(
173
+ x, weight, bias=bias, stride=1, padding=1,
174
+ output_padding=0, groups=1, dilation=1)
175
+ value = torch.nn.functional.batch_norm(
176
+ value, running_mean=None, running_var=None,
177
+ weight=value.new_ones((128,)), bias=value.new_zeros((128,)),
178
+ training=True, momentum=0.1, eps=1e-5)
179
+ value = torch.tanh(value)
180
+ value = torch.nn.functional.max_pool2d(
181
+ value, kernel_size=2, stride=2, padding=0, dilation=1,
182
+ ceil_mode=False)
183
+ return torch.nn.functional.group_norm(
184
+ value, num_groups=8, weight=value.new_ones((128,)),
185
+ bias=value.new_zeros((128,)), eps=1e-5)
186
+
187
+ def launch(inputs, torch_module):
188
+ x = inputs[0]
189
+ batches, channels, input_height, input_width = x.shape
190
+ if channels != 64:
191
+ raise ValueError("level2 problem 11 requires 64 input channels")
192
+ conv_height = input_height + 2
193
+ conv_width = input_width + 2
194
+ pool_height = conv_height // 2
195
+ pool_width = conv_width // 2
196
+ workspace = torch_module.empty(
197
+ (batches, 128, conv_height, conv_width),
198
+ device=x.device, dtype=x.dtype)
199
+ out = torch_module.empty(
200
+ (batches, 128, pool_height, pool_width),
201
+ device=x.device, dtype=x.dtype)
202
+ # Keep allocations and frozen parameters alive through asynchronous use.
203
+ weight, bias = parameters_for(x)
204
+ out._substrate_keepalive = (workspace, weight, bias)
205
+ args = [
206
+ (ctypes.c_void_p, workspace.data_ptr()),
207
+ (ctypes.c_void_p, weight.data_ptr()),
208
+ (ctypes.c_void_p, bias.data_ptr()),
209
+ (ctypes.c_int, batches),
210
+ (ctypes.c_int, input_height),
211
+ (ctypes.c_int, input_width),
212
+ (ctypes.c_int, conv_height),
213
+ (ctypes.c_int, conv_width),
214
+ (ctypes.c_int, pool_height),
215
+ (ctypes.c_int, pool_width),
216
+ ]
217
+ return out, (1, 1, 1), (256, 1, 1), args
218
+
219
+ def suites():
220
+ def t0_original(trial):
221
+ torch.manual_seed(1000 + trial)
222
+ return [torch.rand(512, 64, 32, 32)]
223
+
224
+ def t1_signed(trial):
225
+ torch.manual_seed(2000 + trial)
226
+ return [torch.randn(3, 64, 9, 13)]
227
+
228
+ def t2_misaligned(trial):
229
+ torch.manual_seed(3000 + trial)
230
+ return [torch.rand(5, 64, 11, 15)]
231
+
232
+ def t3_positive_spikes(trial):
233
+ torch.manual_seed(4000 + trial)
234
+ x = torch.rand(2, 64, 10, 14)
235
+ x[:, :, 0, 0] = 25.0
236
+ x[:, :, -1, -1] = 50.0
237
+ return [x]
238
+
239
+ def t4_zero_variance_ties(trial):
240
+ torch.manual_seed(5000 + trial)
241
+ return [torch.zeros(7, 64, 7, 9)]
242
+
243
+ def t5_lane_alternating_magnitude(trial):
244
+ torch.manual_seed(6000 + trial)
245
+ x = torch.empty(5, 64, 13, 17)
246
+ positions = torch.arange(x.numel(), dtype=x.dtype).reshape_as(x)
247
+ x.copy_(torch.where((positions.to(torch.int64) & 1) == 0,
248
+ torch.full_like(x, 1.0e-4),
249
+ torch.full_like(x, 300.0)))
250
+ return [x]
251
+
252
+ def t6_positive_positional_spikes(trial):
253
+ torch.manual_seed(7000 + trial)
254
+ y = torch.arange(15, dtype=torch.float32).view(1, 1, 15, 1)
255
+ xcoord = torch.arange(19, dtype=torch.float32).view(1, 1, 1, 19)
256
+ channel = torch.arange(64, dtype=torch.float32).view(1, 64, 1, 1)
257
+ x = 100.0 + 3.0 * y + 5.0 * xcoord + (channel % 7) * 11.0
258
+ x = x.expand(4, -1, -1, -1).clone()
259
+ x[:, :, ::4, 1::5] = 1200.0
260
+ return [x]
261
+
262
+ def t7_positive_near_constant_quantization(trial):
263
+ torch.manual_seed(8000 + trial)
264
+ y = torch.arange(10, dtype=torch.float32).view(1, 1, 10, 1)
265
+ xcoord = torch.arange(14, dtype=torch.float32).view(1, 1, 1, 14)
266
+ channel = torch.arange(64, dtype=torch.float32).view(1, 64, 1, 1)
267
+ batch = torch.arange(3, dtype=torch.float32).view(3, 1, 1, 1)
268
+ x = (192.0 + 0.03125 * ((3.0 * y + 5.0 * xcoord
269
+ + channel + 7.0 * batch) % 17.0))
270
+ return [x.contiguous()]
271
+
272
+ def t8_batch_lane_stripes(trial):
273
+ torch.manual_seed(9000 + trial)
274
+ batch = torch.arange(129, dtype=torch.int64).view(129, 1, 1, 1)
275
+ channel = torch.arange(64, dtype=torch.int64).view(1, 64, 1, 1)
276
+ y = torch.arange(2, dtype=torch.int64).view(1, 1, 2, 1)
277
+ xcoord = torch.arange(2, dtype=torch.int64).view(1, 1, 1, 2)
278
+ stripe = (batch + channel + 2 * y + xcoord) & 1
279
+ x = torch.where(stripe == 0,
280
+ torch.full(stripe.shape, 1.0e-3),
281
+ torch.full(stripe.shape, 900.0))
282
+ return [x]
283
+
284
+ def t9_tied_pool_spikes(trial):
285
+ torch.manual_seed(10000 + trial)
286
+ x = torch.full((4, 64, 6, 10), 0.125)
287
+ x[:, ::2, ::2, ::2] = 700.0
288
+ x[:, 1::2, 1::2, 1::2] = 700.0
289
+ x[:, :, 2:4, 4:6] = 1400.0
290
+ return [x]
291
+
292
+ return [
293
+ ("T0_original", 5, t0_original),
294
+ ("T1_signed", 1, t1_signed),
295
+ ("T2_misaligned", 1, t2_misaligned),
296
+ ("T3_positive_spikes", 1, t3_positive_spikes),
297
+ ("T4_zero_variance_ties", 1, t4_zero_variance_ties),
298
+ ("T5_lane_alternating_magnitude", 1, t5_lane_alternating_magnitude),
299
+ ("T6_positive_positional_spikes", 1, t6_positive_positional_spikes),
300
+ ("T7_positive_near_constant_quantization", 1, t7_positive_near_constant_quantization),
301
+ ("T8_batch_lane_stripes", 1, t8_batch_lane_stripes),
302
+ ("T9_tied_pool_spikes", 1, t9_tied_pool_spikes),
303
+ ]
304
+
305
+ def probe(torch_module):
306
+ torch_module.manual_seed(0)
307
+ return [
308
+ ("p_aligned", [torch_module.rand(2, 64, 14, 14)]),
309
+ ("p_misaligned", [torch_module.randn(1, 64, 7, 11)]),
310
+ ]
311
+
312
+ K.PROBLEMS["L2p11_convtranspose2d_batchn"] = dict(
313
+ kb_file="11_ConvTranspose2d_BatchNorm_Tanh_MaxPool_GroupNorm.py",
314
+ cuda=cuda_source,
315
+ kernel_name="L2p11_convtranspose2d_batchn_kernel",
316
+ ref=ref,
317
+ launch=launch,
318
+ suites=suites,
319
+ probe=probe,
320
+ )
substrates/candidate_L2p12_gemm_multiply_leakyrel.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Correct, mutation-friendly substrate for KernelBench level2 problem 12."""
2
+
3
+
4
+ def register(K, torch, ctypes):
5
+ cuda_source = r"""
6
+ #include <cuda_fp16.h>
7
+
8
+ __global__ void gemm_multiply_leakyrelu_kernel(
9
+ const float* x, float* out, const float* weight, const float* bias,
10
+ int rows, int input_features, int output_features,
11
+ float multiplier, float negative_slope) {
12
+ long long output_index =
13
+ (long long)blockIdx.x * blockDim.x + threadIdx.x;
14
+ long long output_elements = (long long)rows * output_features;
15
+ if (output_index >= output_elements) return;
16
+
17
+ int row = (int)(output_index / output_features);
18
+ int output_feature = (int)(output_index % output_features);
19
+
20
+ // nn.Linear computes x @ weight.T + bias. Keeping the dot product
21
+ // explicit makes indexing, accumulation, bias, and activation mutations
22
+ // independently visible.
23
+ float accumulator = 0.0f;
24
+ for (int input_feature = 0;
25
+ input_feature < input_features;
26
+ input_feature++) {
27
+ long long input_index =
28
+ (long long)row * input_features + input_feature;
29
+ long long weight_index =
30
+ (long long)output_feature * input_features + input_feature;
31
+ accumulator += x[input_index] * weight[weight_index];
32
+ }
33
+
34
+ float gemm_value = accumulator + bias[output_feature];
35
+ float multiplied_value = gemm_value * multiplier;
36
+ float activated_value = multiplied_value >= 0.0f
37
+ ? multiplied_value
38
+ : multiplied_value * negative_slope;
39
+ out[output_index] = activated_value;
40
+ }
41
+ """
42
+
43
+ input_features = 8192
44
+ output_features = 8192
45
+ multiplier = 2.0
46
+ negative_slope = 0.1
47
+
48
+ # The KernelBench module owns randomly initialized Linear parameters.
49
+ # Freeze one normal reset_parameters result, while preserving the caller's
50
+ # RNG state, then use the identical parameters in both implementations.
51
+ with torch.random.fork_rng(devices=[]):
52
+ torch.manual_seed(0)
53
+ linear = torch.nn.Linear(input_features, output_features, bias=True)
54
+ frozen_weight = linear.weight.detach().cpu().contiguous()
55
+ frozen_bias = linear.bias.detach().cpu().contiguous()
56
+
57
+ device_parameters = {}
58
+
59
+ def parameters_for(x):
60
+ key = (x.device.type, x.device.index, x.dtype)
61
+ parameters = device_parameters.get(key)
62
+ if parameters is None:
63
+ parameters = (
64
+ frozen_weight.to(device=x.device, dtype=x.dtype),
65
+ frozen_bias.to(device=x.device, dtype=x.dtype),
66
+ )
67
+ device_parameters[key] = parameters
68
+ return parameters
69
+
70
+ def ref(x):
71
+ weight, bias = parameters_for(x)
72
+ value = torch.nn.functional.linear(x, weight, bias)
73
+ value = value * multiplier
74
+ return torch.nn.functional.leaky_relu(
75
+ value, negative_slope=negative_slope
76
+ )
77
+
78
+ def launch(inputs, torch_module):
79
+ x = inputs[0]
80
+ if x.ndim != 2 or x.shape[1] != input_features:
81
+ raise ValueError(
82
+ "expected a 2D input whose second dimension is 8192"
83
+ )
84
+
85
+ rows = x.shape[0]
86
+ weight, bias = parameters_for(x)
87
+ out = torch_module.empty(
88
+ (rows, output_features), device=x.device, dtype=x.dtype
89
+ )
90
+ output_elements = out.numel()
91
+ args = [
92
+ (ctypes.c_void_p, weight.data_ptr()),
93
+ (ctypes.c_void_p, bias.data_ptr()),
94
+ (ctypes.c_int, rows),
95
+ (ctypes.c_int, input_features),
96
+ (ctypes.c_int, output_features),
97
+ (ctypes.c_float, multiplier),
98
+ (ctypes.c_float, negative_slope),
99
+ ]
100
+ grid = ((output_elements + 255) // 256, 1, 1)
101
+ return out, grid, (256, 1, 1), args
102
+
103
+ def suites():
104
+ def t0_original(trial):
105
+ torch.manual_seed(1000 + trial)
106
+ return [torch.rand(1024, 8192)]
107
+
108
+ def t1_signed(trial):
109
+ torch.manual_seed(2000 + trial)
110
+ return [torch.randn(17, 8192) * 0.05]
111
+
112
+ def t2_misaligned(trial):
113
+ torch.manual_seed(3000 + trial)
114
+ return [torch.rand(13, 8192)]
115
+
116
+ def t3_positive_tail_spikes(trial):
117
+ torch.manual_seed(4000 + trial)
118
+ x = torch.rand(9, 8192)
119
+ x[:, -1] = 100.0
120
+ x[-1, -32:] = 50.0
121
+ return [x]
122
+
123
+ def t4_positive_first_feature_overflow(trial):
124
+ torch.manual_seed(5000 + trial)
125
+ x = torch.zeros(1, 8192)
126
+ x[:, 0] = 2.0e7
127
+ return [x]
128
+
129
+ def t5_positive_last_feature_overflow(trial):
130
+ torch.manual_seed(6000 + trial)
131
+ x = torch.zeros(3, 8192)
132
+ x[:, -1] = 2.0e7
133
+ return [x]
134
+
135
+ return [
136
+ ("T0_original", 5, t0_original),
137
+ ("T1_signed", 1, t1_signed),
138
+ ("T2_misaligned", 1, t2_misaligned),
139
+ ("T3_positive_tail_spikes", 1, t3_positive_tail_spikes),
140
+ ("T4_positive_first_feature_overflow", 1, t4_positive_first_feature_overflow),
141
+ ("T5_positive_last_feature_overflow", 1, t5_positive_last_feature_overflow),
142
+ ]
143
+
144
+ def probe(torch_module):
145
+ torch_module.manual_seed(0)
146
+ return [
147
+ ("p_aligned", [torch_module.rand(16, 8192)]),
148
+ ("p_misaligned", [torch_module.randn(3, 8192) * 0.05]),
149
+ ]
150
+
151
+ K.PROBLEMS["L2p12_gemm_multiply_leakyrel"] = dict(
152
+ kb_file="12_Gemm_Multiply_LeakyReLU.py",
153
+ cuda=cuda_source,
154
+ kernel_name="gemm_multiply_leakyrelu_kernel",
155
+ ref=ref,
156
+ launch=launch,
157
+ suites=suites,
158
+ probe=probe,
159
+ )
substrates/candidate_L2p13_convtranspose3d_mean_a.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Mutation-friendly substrate for KernelBench level2 problem 13."""
2
+
3
+
4
+ CUDA_SOURCE = r"""
5
+ #include <cuda_fp16.h>
6
+ #include <math_constants.h>
7
+
8
+ __global__ void l2p13_convtranspose3d_mean_a_kernel(
9
+ const float* x, float* out, const float* weight,
10
+ const float* convolution_bias, const float* added_bias,
11
+ int batches, int input_depth, int height, int width,
12
+ long long spatial_rows) {
13
+ long long row = (long long)blockIdx.x;
14
+ int output_channel = threadIdx.x;
15
+ if (row >= spatial_rows || output_channel >= 64) return;
16
+
17
+ long long position = row;
18
+ int output_x = (int)(position % width);
19
+ position /= width;
20
+ int output_y = (int)(position % height);
21
+ int batch = (int)(position / height);
22
+
23
+ // One block owns all 64 channels at one (batch, y, x) location. Each
24
+ // thread first computes the depth-mean of its transposed-convolution
25
+ // channel. For stride=1 and padding=1, iz contributes to oz=iz-1+kz.
26
+ float depth_sum = 0.0f;
27
+ for (int output_z = 0; output_z < input_depth; output_z++) {
28
+ float convolution_sum = 0.0f;
29
+ for (int input_channel = 0; input_channel < 16; input_channel++) {
30
+ for (int kernel_z = 0; kernel_z < 3; kernel_z++) {
31
+ int input_z = output_z + 1 - kernel_z;
32
+ if (input_z < 0 || input_z >= input_depth) continue;
33
+ for (int kernel_y = 0; kernel_y < 3; kernel_y++) {
34
+ int input_y = output_y + 1 - kernel_y;
35
+ if (input_y < 0 || input_y >= height) continue;
36
+ for (int kernel_x = 0; kernel_x < 3; kernel_x++) {
37
+ int input_x = output_x + 1 - kernel_x;
38
+ if (input_x < 0 || input_x >= width) continue;
39
+ long long input_index =
40
+ ((((long long)batch * 16 + input_channel)
41
+ * input_depth + input_z) * height + input_y)
42
+ * width + input_x;
43
+ // ConvTranspose3d weights use [Cin, Cout, Kd, Kh, Kw].
44
+ long long weight_index =
45
+ (((((long long)input_channel * 64 + output_channel)
46
+ * 3 + kernel_z) * 3 + kernel_y) * 3 + kernel_x);
47
+ convolution_sum += x[input_index] * weight[weight_index];
48
+ }
49
+ }
50
+ }
51
+ }
52
+ depth_sum += convolution_sum + convolution_bias[output_channel];
53
+ }
54
+
55
+ __shared__ float logits[64];
56
+ __shared__ float probabilities[64];
57
+ __shared__ float channel_max;
58
+ __shared__ float exponential_sum;
59
+ logits[output_channel] = depth_sum / (float)input_depth
60
+ + added_bias[output_channel];
61
+ __syncthreads(); // sync-after-logits
62
+
63
+ if (output_channel == 0) {
64
+ float maximum = -CUDART_INF_F;
65
+ for (int channel = 0; channel < 64; channel++) {
66
+ maximum = fmaxf(maximum, logits[channel]);
67
+ }
68
+ channel_max = maximum;
69
+ }
70
+ __syncthreads(); // sync-after-maximum
71
+
72
+ probabilities[output_channel] = expf(logits[output_channel] - channel_max);
73
+ __syncthreads(); // sync-after-exponentials
74
+
75
+ if (output_channel == 0) {
76
+ float sum = 0.0f;
77
+ for (int channel = 0; channel < 64; channel++) {
78
+ sum += probabilities[channel];
79
+ }
80
+ exponential_sum = sum;
81
+ }
82
+ __syncthreads(); // sync-after-sum
83
+
84
+ float probability = probabilities[output_channel] / exponential_sum;
85
+ // Rewrite row-major [B,H,W,C] indexing into contiguous [B,C,1,H,W].
86
+ long long plane = (long long)height * width;
87
+ long long output_spatial = row % plane;
88
+ long long output_batch = row / plane;
89
+ long long output_index =
90
+ (output_batch * 64 + output_channel) * plane + output_spatial;
91
+ out[output_index] = tanhf(probability) * 2.0f;
92
+ }
93
+ """
94
+
95
+
96
+ def register(K, torch, ctypes):
97
+ # Match construction order exactly: ConvTranspose3d initializes its weight
98
+ # and bias first, then Model initializes its separate broadcast bias.
99
+ with torch.random.fork_rng(devices=[]):
100
+ torch.manual_seed(0)
101
+ convolution = torch.nn.ConvTranspose3d(
102
+ 16, 64, 3, stride=1, padding=1
103
+ )
104
+ frozen_weight = convolution.weight.detach().cpu().contiguous()
105
+ frozen_convolution_bias = convolution.bias.detach().cpu().contiguous()
106
+ frozen_added_bias = torch.randn(1, 64, 1, 1, 1).cpu().contiguous()
107
+
108
+ parameter_cache = {}
109
+
110
+ def parameters_for(x):
111
+ key = (x.device.type, x.device.index, x.dtype)
112
+ parameters = parameter_cache.get(key)
113
+ if parameters is None:
114
+ parameters = (
115
+ frozen_weight.to(device=x.device, dtype=x.dtype),
116
+ frozen_convolution_bias.to(device=x.device, dtype=x.dtype),
117
+ frozen_added_bias.to(device=x.device, dtype=x.dtype),
118
+ )
119
+ parameter_cache[key] = parameters
120
+ return parameters
121
+
122
+ def ref(x):
123
+ weight, convolution_bias, added_bias = parameters_for(x)
124
+ value = torch.nn.functional.conv_transpose3d(
125
+ x, weight, bias=convolution_bias, stride=1, padding=1,
126
+ output_padding=0, groups=1, dilation=1,
127
+ )
128
+ value = value.mean(dim=2, keepdim=True)
129
+ value = value + added_bias
130
+ value = torch.softmax(value, dim=1)
131
+ value = torch.tanh(value)
132
+ return value * 2.0
133
+
134
+ def launch(inputs, torch_module):
135
+ x = inputs[0]
136
+ batches, input_channels, input_depth, height, width = x.shape
137
+ if input_channels != 16:
138
+ raise ValueError("level2 problem 13 requires exactly 16 input channels")
139
+ if input_depth < 1:
140
+ raise ValueError("level2 problem 13 requires nonempty depth")
141
+
142
+ out = torch_module.empty(
143
+ (batches, 64, 1, height, width), device=x.device, dtype=x.dtype
144
+ )
145
+ weight, convolution_bias, added_bias = parameters_for(x)
146
+ spatial_rows = batches * height * width
147
+ args = [
148
+ (ctypes.c_void_p, weight.data_ptr()),
149
+ (ctypes.c_void_p, convolution_bias.data_ptr()),
150
+ (ctypes.c_void_p, added_bias.data_ptr()),
151
+ (ctypes.c_int, batches),
152
+ (ctypes.c_int, input_depth),
153
+ (ctypes.c_int, height),
154
+ (ctypes.c_int, width),
155
+ (ctypes.c_longlong, spatial_rows),
156
+ ]
157
+ return out, (spatial_rows, 1, 1), (64, 1, 1), args
158
+
159
+ def suites():
160
+ def t0_original(trial):
161
+ torch.manual_seed(1000 + trial)
162
+ return [torch.rand(16, 16, 32, 128, 128)]
163
+
164
+ def t1_signed(trial):
165
+ torch.manual_seed(2000 + trial)
166
+ return [torch.randn(2, 16, 5, 7, 9)]
167
+
168
+ def t2_misaligned(trial):
169
+ torch.manual_seed(3000 + trial)
170
+ return [torch.rand(3, 16, 6, 10, 13)]
171
+
172
+ def t3_positive_spikes(trial):
173
+ torch.manual_seed(4000 + trial)
174
+ x = torch.rand(1, 16, 7, 9, 11)
175
+ x[:, :, 0, 0, 0] = 25.0
176
+ x[:, :, 3, 4, 5] = 50.0
177
+ x[:, :, -1, -1, -1] = 100.0
178
+ return [x]
179
+
180
+ def t4_reduction_endpoint_mass(trial):
181
+ torch.manual_seed(5000 + trial)
182
+ x = torch.full((1, 16, 2, 3, 5), 1.0e-3)
183
+ x[:, 0, 0, :, :] = 1200.0
184
+ x[:, -1, -1, :, :] = 2400.0
185
+ return [x]
186
+
187
+ def endpoint_channel_input(target, seed):
188
+ # With a single voxel only the centre kernel coefficient is used.
189
+ # A nonnegative direction away from the other channels makes the
190
+ # selected endpoint channel dominate without cancellation-prone
191
+ # signed, high-magnitude inputs.
192
+ torch.manual_seed(seed)
193
+ centre = frozen_weight[:, :, 1, 1, 1]
194
+ direction = (centre[:, target] - centre.mean(dim=1)).clamp_min(0)
195
+ direction = direction + torch.rand(16) * 1.0e-6
196
+ return [direction.mul(100000.0).reshape(1, 16, 1, 1, 1)]
197
+
198
+ def t5_channel0_crosswarp_extreme(trial):
199
+ return endpoint_channel_input(0, 6000 + trial)
200
+
201
+ def t6_channel63_crosswarp_extreme(trial):
202
+ return endpoint_channel_input(63, 7000 + trial)
203
+
204
+ def t7_spatial_kernel_endpoint_mass(trial):
205
+ torch.manual_seed(8000 + trial)
206
+ x = torch.full((1, 16, 3, 3, 3), 1.0e-3)
207
+ # Opposite corners exercise both the first and last iterations of
208
+ # each 3-tap spatial kernel loop at boundary output positions.
209
+ x[:, :, 0, 0, 0] = 3000.0
210
+ x[:, :, -1, -1, -1] = 1500.0
211
+ return [x]
212
+
213
+ def t8_depth_endpoint_planes(trial):
214
+ torch.manual_seed(9000 + trial)
215
+ x = torch.full((1, 16, 3, 2, 3), 1.0e-3)
216
+ # Unequal endpoint planes make dropping either an output-depth or
217
+ # kernel-depth endpoint change the mean substantially.
218
+ x[:, :, 0, :, :] = 3000.0
219
+ x[:, :, -1, :, :] = 750.0
220
+ return [x]
221
+
222
+ def t9_alternating_lane_contrast(trial):
223
+ torch.manual_seed(10000 + trial)
224
+ x = torch.full((1, 16, 1, 3, 5), 1.0e-3)
225
+ # High/low input-channel neighbours create sharply different
226
+ # partial sums while remaining same-sign for stable accumulation.
227
+ x[:, 0::2, :, :, :] = 3000.0
228
+ x[:, 1::2, :, :, :] = 1.0e-4
229
+ x[:, :, :, 0::2, 0::2] *= 0.25
230
+ return [x]
231
+
232
+ return [
233
+ ("T0_original", 5, t0_original),
234
+ ("T1_signed", 1, t1_signed),
235
+ ("T2_misaligned", 1, t2_misaligned),
236
+ ("T3_positive_spikes", 1, t3_positive_spikes),
237
+ ("T4_reduction_endpoint_mass", 1, t4_reduction_endpoint_mass),
238
+ ("T5_channel0_crosswarp_extreme", 1, t5_channel0_crosswarp_extreme),
239
+ ("T6_channel63_crosswarp_extreme", 1, t6_channel63_crosswarp_extreme),
240
+ ("T7_spatial_kernel_endpoint_mass", 1, t7_spatial_kernel_endpoint_mass),
241
+ ("T8_depth_endpoint_planes", 1, t8_depth_endpoint_planes),
242
+ ("T9_alternating_lane_contrast", 1, t9_alternating_lane_contrast),
243
+ ]
244
+
245
+ def probe(torch_module):
246
+ torch_module.manual_seed(0)
247
+ return [
248
+ ("p_aligned", [torch_module.rand(1, 16, 4, 8, 8)]),
249
+ ("p_misaligned", [torch_module.randn(2, 16, 5, 7, 9)]),
250
+ ]
251
+
252
+ K.PROBLEMS["L2p13_convtranspose3d_mean_a"] = dict(
253
+ kb_file="13_ConvTranspose3d_Mean_Add_Softmax_Tanh_Scaling.py",
254
+ cuda=CUDA_SOURCE,
255
+ kernel_name="l2p13_convtranspose3d_mean_a_kernel",
256
+ ref=ref,
257
+ launch=launch,
258
+ suites=suites,
259
+ probe=probe,
260
+ )
substrates/candidate_L2p14_gemm_divide_sum_scalin.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Mutation-friendly substrate for KernelBench level2 problem 14."""
2
+
3
+
4
+ CUDA_SOURCE = r"""
5
+ #include <cuda_fp16.h>
6
+
7
+ __global__ void gemm_divide_sum_scaling_kernel(
8
+ const float* x, float* out, const float* weight,
9
+ int batch_size, int input_size, int hidden_size) {
10
+ int batch = blockIdx.x;
11
+ int tid = threadIdx.x;
12
+ if (batch >= batch_size) return;
13
+
14
+ // Each thread computes complete GEMM entries for a strided subset of
15
+ // hidden columns. Keeping the inner-product loop explicit provides clear
16
+ // mutation sites for both bounds and the two matrix strides.
17
+ float thread_sum = 0.0f;
18
+ for (int hidden = tid; hidden < hidden_size; hidden += blockDim.x) {
19
+ float gemm_value = 0.0f;
20
+ for (int inner = 0; inner < input_size; inner++) {
21
+ long long x_index = (long long)batch * input_size + inner;
22
+ long long weight_index =
23
+ (long long)hidden * input_size + inner;
24
+ gemm_value += x[x_index] * weight[weight_index];
25
+ }
26
+ float divided_value = gemm_value / 2.0f;
27
+ thread_sum += divided_value;
28
+ }
29
+
30
+ __shared__ float partial_sums[256];
31
+ partial_sums[tid] = thread_sum;
32
+ __syncthreads(); // sync-after-partial-store
33
+
34
+ for (int width = 128; width > 0; width >>= 1) {
35
+ if (tid < width) {
36
+ partial_sums[tid] =
37
+ partial_sums[tid] + partial_sums[tid + width];
38
+ }
39
+ __syncthreads(); // sync-after-reduction-step
40
+ }
41
+
42
+ if (tid == 0) {
43
+ out[batch] = partial_sums[0] * 1.5f;
44
+ }
45
+ }
46
+ """
47
+
48
+
49
+ def register(K, torch, ctypes):
50
+ # Model.__init__ calls torch.randn(8192, 8192) exactly once. Freeze an
51
+ # ordinary seed-0 realization so the implicit parameter is identical in
52
+ # the reference and device paths without perturbing suite RNG state.
53
+ with torch.random.fork_rng(devices=[]):
54
+ torch.manual_seed(0)
55
+ frozen_weight = torch.randn(8192, 8192).contiguous()
56
+
57
+ device_weights = {}
58
+
59
+ def weight_for(x):
60
+ key = (x.device.type, x.device.index, x.dtype)
61
+ weight = device_weights.get(key)
62
+ if weight is None:
63
+ weight = frozen_weight.to(device=x.device, dtype=x.dtype)
64
+ device_weights[key] = weight
65
+ return weight
66
+
67
+ def ref(x):
68
+ # Forward is matmul, true division, sum over hidden dim with keepdim,
69
+ # then multiplication by get_init_inputs()' scaling_factor=1.5.
70
+ value = torch.matmul(x, weight_for(x).T)
71
+ value = value / 2
72
+ value = torch.sum(value, dim=1, keepdim=True)
73
+ return value * 1.5
74
+
75
+ def launch(inputs, torch_module):
76
+ x = inputs[0]
77
+ if x.ndim != 2 or x.shape[1] != 8192:
78
+ raise ValueError("this substrate requires input shape (batch, 8192)")
79
+
80
+ batch_size, input_size = x.shape
81
+ hidden_size = 8192
82
+ out = torch_module.empty(
83
+ (batch_size, 1), device=x.device, dtype=x.dtype)
84
+ args = [
85
+ (ctypes.c_void_p, weight_for(x).data_ptr()),
86
+ (ctypes.c_int, batch_size),
87
+ (ctypes.c_int, input_size),
88
+ (ctypes.c_int, hidden_size),
89
+ ]
90
+ return out, (batch_size, 1, 1), (256, 1, 1), args
91
+
92
+ def suites():
93
+ def t0_original(trial):
94
+ torch.manual_seed(1000 + trial)
95
+ return [torch.rand(1024, 8192)]
96
+
97
+ def t1_signed(trial):
98
+ torch.manual_seed(2000 + trial)
99
+ return [torch.randn(9, 8192) * 0.1]
100
+
101
+ def t2_misaligned_batch(trial):
102
+ torch.manual_seed(3000 + trial)
103
+ return [torch.rand(37, 8192)]
104
+
105
+ def t3_positive_tail_spike(trial):
106
+ torch.manual_seed(4000 + trial)
107
+ x = torch.rand(5, 8192)
108
+ x[:, -1] = 100.0
109
+ return [x]
110
+
111
+ def t4_positive_structured_overflow(trial):
112
+ torch.manual_seed(5000 + trial)
113
+ position = torch.linspace(0.0, 1.0, 8192)
114
+ x = torch.stack([
115
+ torch.full((8192,), 32.0),
116
+ 16.0 + 32.0 * position,
117
+ torch.where(
118
+ torch.arange(8192) % 2 == 0,
119
+ torch.tensor(8.0),
120
+ torch.tensor(56.0)),
121
+ ])
122
+ return [x]
123
+
124
+ def t5_positive_periodic_spikes(trial):
125
+ torch.manual_seed(6000 + trial)
126
+ x = torch.full((7, 8192), 64.0)
127
+ x[:, ::257] = 2048.0
128
+ return [x]
129
+
130
+ return [
131
+ ("T0_original", 5, t0_original),
132
+ ("T1_signed", 1, t1_signed),
133
+ ("T2_misaligned_batch", 1, t2_misaligned_batch),
134
+ ("T3_positive_tail_spike", 1, t3_positive_tail_spike),
135
+ ("T4_positive_structured_overflow", 1,
136
+ t4_positive_structured_overflow),
137
+ ("T5_positive_periodic_spikes", 1,
138
+ t5_positive_periodic_spikes),
139
+ ]
140
+
141
+ def probe(torch_module):
142
+ torch_module.manual_seed(0)
143
+ return [
144
+ ("p_aligned", [torch_module.rand(16, 8192)]),
145
+ ("p_misaligned", [torch_module.randn(7, 8192) * 0.1]),
146
+ ]
147
+
148
+ K.PROBLEMS["L2p14_gemm_divide_sum_scalin"] = dict(
149
+ kb_file="14_Gemm_Divide_Sum_Scaling.py",
150
+ cuda=CUDA_SOURCE,
151
+ kernel_name="gemm_divide_sum_scaling_kernel",
152
+ ref=ref,
153
+ launch=launch,
154
+ suites=suites,
155
+ probe=probe,
156
+ )
substrates/candidate_L2p15_convtranspose3d_batchn.py ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Mutation-friendly substrate for KernelBench level 2 problem 15."""
2
+
3
+
4
+ CUDA_SOURCE = r"""
5
+ #include <cuda_fp16.h>
6
+
7
+ __global__ void L2p15_convtranspose3d_batchn_kernel(
8
+ const float* x, float* out, const float* weight, const float* bias,
9
+ int batches, int input_depth, int input_height, int input_width,
10
+ int output_depth, int output_height, int output_width) {
11
+ int output_channel = blockIdx.x;
12
+ int tid = threadIdx.x;
13
+ long long input_spatial =
14
+ (long long)input_depth * input_height * input_width;
15
+ long long output_spatial =
16
+ (long long)output_depth * output_height * output_width;
17
+ long long channel_elements = (long long)batches * output_spatial;
18
+ long long passes = (channel_elements + 255) / 256;
19
+ __shared__ float partial[256];
20
+
21
+ // First materialize ConvTranspose3d. Its weight layout is
22
+ // [input_channel, output_channel, kz, ky, kx].
23
+ float local_sum = 0.0f;
24
+ for (long long pass = 0; pass < passes; pass++) {
25
+ long long channel_index = pass * 256 + tid;
26
+ if (channel_index < channel_elements) {
27
+ int batch = (int)(channel_index / output_spatial);
28
+ long long spatial_index = channel_index % output_spatial;
29
+ int output_x = (int)(spatial_index % output_width);
30
+ spatial_index /= output_width;
31
+ int output_y = (int)(spatial_index % output_height);
32
+ int output_z = (int)(spatial_index / output_height);
33
+
34
+ float value = bias[output_channel];
35
+ for (int input_channel = 0; input_channel < 16; input_channel++) {
36
+ for (int kernel_z = 0; kernel_z < 3; kernel_z++) {
37
+ int z_numerator = output_z + 1 - kernel_z;
38
+ if (z_numerator < 0 || (z_numerator & 1)) continue;
39
+ int input_z = z_numerator / 2;
40
+ if (input_z >= input_depth) continue;
41
+ for (int kernel_y = 0; kernel_y < 3; kernel_y++) {
42
+ int y_numerator = output_y + 1 - kernel_y;
43
+ if (y_numerator < 0 || (y_numerator & 1)) continue;
44
+ int input_y = y_numerator / 2;
45
+ if (input_y >= input_height) continue;
46
+ for (int kernel_x = 0; kernel_x < 3; kernel_x++) {
47
+ int x_numerator = output_x + 1 - kernel_x;
48
+ if (x_numerator < 0 || (x_numerator & 1)) continue;
49
+ int input_x = x_numerator / 2;
50
+ if (input_x >= input_width) continue;
51
+
52
+ long long input_index =
53
+ (long long)batch * 16 * input_spatial
54
+ + (long long)input_channel * input_spatial
55
+ + ((long long)input_z * input_height + input_y)
56
+ * input_width + input_x;
57
+ long long weight_index =
58
+ (((((long long)input_channel * 32
59
+ + output_channel) * 3 + kernel_z) * 3
60
+ + kernel_y) * 3 + kernel_x);
61
+ value += x[input_index] * weight[weight_index];
62
+ }
63
+ }
64
+ }
65
+ }
66
+ long long output_index =
67
+ (long long)batch * 32 * output_spatial
68
+ + (long long)output_channel * output_spatial
69
+ + channel_index % output_spatial;
70
+ out[output_index] = value;
71
+ local_sum += value;
72
+ }
73
+ }
74
+ partial[tid] = local_sum;
75
+ __syncthreads(); // sync-after-global-sum-store
76
+ for (int offset = 128; offset > 0; offset >>= 1) {
77
+ if (tid < offset) { partial[tid] += partial[tid + offset]; }
78
+ __syncthreads(); // sync-during-global-sum-reduction
79
+ }
80
+ float global_mean = partial[0] / (float)channel_elements;
81
+
82
+ // BatchNorm3d uses the biased, population variance for its output.
83
+ float local_square_deviation = 0.0f;
84
+ for (long long pass = 0; pass < passes; pass++) {
85
+ long long channel_index = pass * 256 + tid;
86
+ if (channel_index < channel_elements) {
87
+ int batch = (int)(channel_index / output_spatial);
88
+ long long spatial_index = channel_index % output_spatial;
89
+ long long output_index =
90
+ (long long)batch * 32 * output_spatial
91
+ + (long long)output_channel * output_spatial + spatial_index;
92
+ float centered = out[output_index] - global_mean;
93
+ local_square_deviation += centered * centered;
94
+ }
95
+ }
96
+ partial[tid] = local_square_deviation;
97
+ __syncthreads(); // sync-after-variance-store
98
+ for (int offset = 128; offset > 0; offset >>= 1) {
99
+ if (tid < offset) { partial[tid] += partial[tid + offset]; }
100
+ __syncthreads(); // sync-during-variance-reduction
101
+ }
102
+ float inverse_std =
103
+ rsqrtf(partial[0] / (float)channel_elements + 1.0e-5f);
104
+ __syncthreads(); // sync-before-sample-loop
105
+
106
+ // Subtracting each sample's spatial mean after BatchNorm cancels the
107
+ // convolution bias, BN beta, and global BN mean. Default BN gamma is 1.
108
+ long long sample_passes = (output_spatial + 255) / 256;
109
+ for (int batch = 0; batch < batches; batch++) {
110
+ float local_sample_sum = 0.0f;
111
+ long long sample_base =
112
+ (long long)batch * 32 * output_spatial
113
+ + (long long)output_channel * output_spatial;
114
+ for (long long pass = 0; pass < sample_passes; pass++) {
115
+ long long spatial_index = pass * 256 + tid;
116
+ if (spatial_index < output_spatial) {
117
+ local_sample_sum += out[sample_base + spatial_index];
118
+ }
119
+ }
120
+ partial[tid] = local_sample_sum;
121
+ __syncthreads(); // sync-after-sample-sum-store
122
+ for (int offset = 128; offset > 0; offset >>= 1) {
123
+ if (tid < offset) { partial[tid] += partial[tid + offset]; }
124
+ __syncthreads(); // sync-during-sample-sum-reduction
125
+ }
126
+ float sample_mean = partial[0] / (float)output_spatial;
127
+ __syncthreads(); // sync-before-sample-write
128
+ for (long long pass = 0; pass < sample_passes; pass++) {
129
+ long long spatial_index = pass * 256 + tid;
130
+ if (spatial_index < output_spatial) {
131
+ float value = out[sample_base + spatial_index];
132
+ out[sample_base + spatial_index] =
133
+ (value - sample_mean) * inverse_std;
134
+ }
135
+ }
136
+ __syncthreads(); // sync-after-sample-write
137
+ }
138
+ }
139
+ """
140
+
141
+
142
+ def register(K, torch, ctypes):
143
+ """Register the device-only kernel and deterministic input families."""
144
+
145
+ # get_init_inputs() is [16, 32, 3, 2, 1], with bias retaining its
146
+ # constructor default True. Freeze one ordinary default initialization
147
+ # for the reference and CUDA paths while preserving the caller's CPU RNG.
148
+ with torch.random.fork_rng(devices=[]):
149
+ torch.manual_seed(0)
150
+ module = torch.nn.ConvTranspose3d(
151
+ 16, 32, 3, stride=2, padding=1, bias=True)
152
+ frozen_weight = module.weight.detach().cpu().contiguous()
153
+ frozen_bias = module.bias.detach().cpu().contiguous()
154
+
155
+ device_parameters = {}
156
+
157
+ def parameters_for(x):
158
+ key = (x.device.type, x.device.index, x.dtype)
159
+ values = device_parameters.get(key)
160
+ if values is None:
161
+ values = (
162
+ frozen_weight.to(device=x.device, dtype=x.dtype),
163
+ frozen_bias.to(device=x.device, dtype=x.dtype),
164
+ )
165
+ device_parameters[key] = values
166
+ return values
167
+
168
+ def ref(x):
169
+ weight, bias = parameters_for(x)
170
+ value = torch.nn.functional.conv_transpose3d(
171
+ x, weight, bias=bias, stride=2, padding=1,
172
+ output_padding=0, groups=1, dilation=1)
173
+ value = torch.nn.functional.batch_norm(
174
+ value, running_mean=None, running_var=None,
175
+ weight=None, bias=None, training=True,
176
+ momentum=0.1, eps=1.0e-5)
177
+ return value - torch.mean(value, dim=(2, 3, 4), keepdim=True)
178
+
179
+ def launch(inputs, torch_module):
180
+ x = inputs[0]
181
+ batches, input_channels, input_depth, input_height, input_width = x.shape
182
+ if input_channels != 16:
183
+ raise ValueError("level 2 problem 15 requires 16 input channels")
184
+ output_depth = 2 * input_depth - 1
185
+ output_height = 2 * input_height - 1
186
+ output_width = 2 * input_width - 1
187
+ out = torch_module.empty(
188
+ (batches, 32, output_depth, output_height, output_width),
189
+ device=x.device, dtype=x.dtype)
190
+ weight, bias = parameters_for(x)
191
+ args = [
192
+ (ctypes.c_void_p, weight.data_ptr()),
193
+ (ctypes.c_void_p, bias.data_ptr()),
194
+ (ctypes.c_int, batches),
195
+ (ctypes.c_int, input_depth),
196
+ (ctypes.c_int, input_height),
197
+ (ctypes.c_int, input_width),
198
+ (ctypes.c_int, output_depth),
199
+ (ctypes.c_int, output_height),
200
+ (ctypes.c_int, output_width),
201
+ ]
202
+ return out, (32, 1, 1), (256, 1, 1), args
203
+
204
+ def suites():
205
+ def t0_original(trial):
206
+ torch.manual_seed(1000 + trial)
207
+ return [torch.rand(16, 16, 16, 32, 32)]
208
+
209
+ def t1_signed(trial):
210
+ torch.manual_seed(2000 + trial)
211
+ return [torch.randn(2, 16, 5, 7, 9)]
212
+
213
+ def t2_misaligned(trial):
214
+ torch.manual_seed(3000 + trial)
215
+ return [torch.rand(3, 16, 4, 6, 11)]
216
+
217
+ def t3_positive_spikes(trial):
218
+ torch.manual_seed(4000 + trial)
219
+ x = torch.rand(2, 16, 5, 7, 9)
220
+ x[:, :, 0, 0, 0] = 20.0
221
+ x[:, :, -1, -1, -1] = 40.0
222
+ return [x]
223
+
224
+ def t4_zero_variance_eps(trial):
225
+ torch.manual_seed(5000 + trial)
226
+ return [torch.zeros(2, 16, 3, 5, 7)]
227
+
228
+ def t5_positive_alternating_lanes(trial):
229
+ torch.manual_seed(6000 + trial)
230
+ x = torch.full((3, 16, 5, 8, 9), 1.0e-3)
231
+ x.view(-1)[1::2] = 3000.0
232
+ return [x]
233
+
234
+ def t6_batch_tail_spikes(trial):
235
+ torch.manual_seed(7000 + trial)
236
+ x = torch.full((5, 16, 4, 6, 11), 1.0e-3)
237
+ x[1::2] = 2000.0
238
+ x[:, :, -1, -1, -1] = 3000.0
239
+ return [x]
240
+
241
+ def t7_small_misaligned_boundary_spikes(trial):
242
+ torch.manual_seed(8000 + trial)
243
+ x = torch.full((7, 16, 2, 3, 5), 2.0e-2)
244
+ x[:, :, 0, 0, 0] = 400.0
245
+ x[:, :, -1, -1, -1] = 2400.0
246
+ x[-1, :, :, :, -1] = 3000.0
247
+ return [x]
248
+
249
+ def t8_positive_spatial_checkerboard(trial):
250
+ torch.manual_seed(9000 + trial)
251
+ x = torch.full((3, 16, 4, 5, 10), 1.0e-3)
252
+ x[:, :, :, :, 1::2] = 1800.0
253
+ x[:, 1::2, 1::2, ::2, :] = 3000.0
254
+ return [x]
255
+
256
+ def t9_batch_channel_positional_ramp(trial):
257
+ torch.manual_seed(10000 + trial)
258
+ x = torch.full((5, 16, 3, 4, 7), 1.0e-2)
259
+ batch = torch.arange(5, dtype=x.dtype).view(5, 1, 1, 1, 1)
260
+ channel = torch.arange(16, dtype=x.dtype).view(1, 16, 1, 1, 1)
261
+ width = torch.arange(7, dtype=x.dtype).view(1, 1, 1, 1, 7)
262
+ x += 120.0 * batch + 35.0 * channel + 210.0 * width
263
+ x[:, :, -1, -1, -1] = 3000.0
264
+ return [x]
265
+
266
+ return [
267
+ ("T0_original", 5, t0_original),
268
+ ("T1_signed", 1, t1_signed),
269
+ ("T2_misaligned", 1, t2_misaligned),
270
+ ("T3_positive_spikes", 1, t3_positive_spikes),
271
+ ("T4_zero_variance_eps", 1, t4_zero_variance_eps),
272
+ ("T5_positive_alternating_lanes", 1,
273
+ t5_positive_alternating_lanes),
274
+ ("T6_batch_tail_spikes", 1, t6_batch_tail_spikes),
275
+ ("T7_small_misaligned_boundary_spikes", 1,
276
+ t7_small_misaligned_boundary_spikes),
277
+ ("T8_positive_spatial_checkerboard", 1,
278
+ t8_positive_spatial_checkerboard),
279
+ ("T9_batch_channel_positional_ramp", 1,
280
+ t9_batch_channel_positional_ramp),
281
+ ]
282
+
283
+ def probe(torch_module):
284
+ torch_module.manual_seed(0)
285
+ return [
286
+ ("p_aligned", [torch_module.rand(1, 16, 4, 8, 8)]),
287
+ ("p_misaligned", [torch_module.randn(2, 16, 3, 5, 7)]),
288
+ ]
289
+
290
+ K.PROBLEMS["L2p15_convtranspose3d_batchn"] = dict(
291
+ kb_file="15_ConvTranspose3d_BatchNorm_Subtract.py",
292
+ cuda=CUDA_SOURCE,
293
+ kernel_name="L2p15_convtranspose3d_batchn_kernel",
294
+ ref=ref,
295
+ launch=launch,
296
+ suites=suites,
297
+ probe=probe,
298
+ )
substrates/candidate_L2p16_convtranspose2d_mish_a.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Mutation-friendly substrate for KernelBench level-2 problem 16."""
2
+
3
+
4
+ CUDA_SOURCE = r"""
5
+ #include <cuda_fp16.h>
6
+
7
+ __global__ void L2p16_convtranspose2d_mish_add_kernel(
8
+ const float* x, float* out, const float* weight, const float* bias,
9
+ int batches, int input_height, int input_width,
10
+ int output_height, int output_width, long long output_elements) {
11
+ long long output_index =
12
+ (long long)blockIdx.x * blockDim.x + threadIdx.x;
13
+ if (output_index >= output_elements) return;
14
+
15
+ long long position = output_index;
16
+ int output_x = (int)(position % output_width);
17
+ position /= output_width;
18
+ int output_y = (int)(position % output_height);
19
+ position /= output_height;
20
+ int output_channel = (int)(position % 64);
21
+ int batch = (int)(position / 64);
22
+
23
+ // ConvTranspose2d parameters baked in from get_init_inputs(): kernel 3,
24
+ // stride 2, padding 1, output_padding 1, with the default bias enabled.
25
+ float accumulator = bias[output_channel];
26
+ for (int input_channel = 0; input_channel < 64; input_channel++) {
27
+ for (int kernel_y = 0; kernel_y < 3; kernel_y++) {
28
+ int input_y_numerator = output_y + 1 - kernel_y;
29
+ if (input_y_numerator % 2 != 0) continue;
30
+ int input_y = input_y_numerator / 2;
31
+ if (input_y < 0 || input_y >= input_height) continue;
32
+
33
+ for (int kernel_x = 0; kernel_x < 3; kernel_x++) {
34
+ int input_x_numerator = output_x + 1 - kernel_x;
35
+ if (input_x_numerator % 2 != 0) continue;
36
+ int input_x = input_x_numerator / 2;
37
+ if (input_x < 0 || input_x >= input_width) continue;
38
+
39
+ long long input_index =
40
+ (((long long)batch * 64 + input_channel) * input_height
41
+ + input_y) * input_width + input_x;
42
+ // ConvTranspose2d weights are (Cin, Cout, Kh, Kw).
43
+ long long weight_index =
44
+ (((long long)input_channel * 64 + output_channel) * 3
45
+ + kernel_y) * 3 + kernel_x;
46
+ accumulator += x[input_index] * weight[weight_index];
47
+ }
48
+ }
49
+ }
50
+
51
+ // Mish(x) = x*tanh(softplus(x)); PyTorch's default softplus threshold is
52
+ // 20. Then add 0.5, clamp to [-1, 1], and multiply by 2.
53
+ float softplus = accumulator > 20.0f
54
+ ? accumulator : log1pf(expf(accumulator));
55
+ float mish = accumulator * tanhf(softplus);
56
+ float added = mish + 0.5f;
57
+ float clamped = fminf(fmaxf(added, -1.0f), 1.0f);
58
+ out[output_index] = clamped * 2.0f;
59
+ }
60
+ """
61
+
62
+
63
+ def register(K, torch, ctypes):
64
+ # Model parameters are state rather than get_inputs() values. Freeze one
65
+ # ordinary default initialization and share it between ref and CUDA while
66
+ # preserving the caller's RNG state.
67
+ with torch.random.fork_rng(devices=[]):
68
+ torch.manual_seed(0)
69
+ layer = torch.nn.ConvTranspose2d(
70
+ 64, 64, 3, stride=2, padding=1, output_padding=1
71
+ )
72
+ frozen_weight = layer.weight.detach().cpu().contiguous()
73
+ frozen_bias = layer.bias.detach().cpu().contiguous()
74
+
75
+ device_parameters = {}
76
+
77
+ def parameters_for(x):
78
+ key = (x.device.type, x.device.index, x.dtype)
79
+ parameters = device_parameters.get(key)
80
+ if parameters is None:
81
+ parameters = (
82
+ frozen_weight.to(device=x.device, dtype=x.dtype),
83
+ frozen_bias.to(device=x.device, dtype=x.dtype),
84
+ )
85
+ device_parameters[key] = parameters
86
+ return parameters
87
+
88
+ def ref(x):
89
+ weight, bias = parameters_for(x)
90
+ value = torch.nn.functional.conv_transpose2d(
91
+ x, weight, bias=bias, stride=2, padding=1, output_padding=1
92
+ )
93
+ value = torch.nn.functional.mish(value)
94
+ value = value + 0.5
95
+ value = torch.nn.functional.hardtanh(value, min_val=-1, max_val=1)
96
+ return value * 2
97
+
98
+ def launch(inputs, torch_module):
99
+ x = inputs[0]
100
+ batches, input_channels, input_height, input_width = x.shape
101
+ if input_channels != 64:
102
+ raise ValueError("level-2 problem 16 requires 64 input channels")
103
+
104
+ output_height = (input_height - 1) * 2 - 2 + 3 + 1
105
+ output_width = (input_width - 1) * 2 - 2 + 3 + 1
106
+ out = torch_module.empty(
107
+ (batches, 64, output_height, output_width),
108
+ device=x.device, dtype=x.dtype,
109
+ )
110
+ weight, bias = parameters_for(x)
111
+ output_elements = out.numel()
112
+ args = [
113
+ (ctypes.c_void_p, weight.data_ptr()),
114
+ (ctypes.c_void_p, bias.data_ptr()),
115
+ (ctypes.c_int, batches),
116
+ (ctypes.c_int, input_height),
117
+ (ctypes.c_int, input_width),
118
+ (ctypes.c_int, output_height),
119
+ (ctypes.c_int, output_width),
120
+ (ctypes.c_longlong, output_elements),
121
+ ]
122
+ grid = ((output_elements + 255) // 256, 1, 1)
123
+ return out, grid, (256, 1, 1), args
124
+
125
+ def suites():
126
+ def t0_original(trial):
127
+ torch.manual_seed(1000 + trial)
128
+ return [torch.rand(128, 64, 128, 128)]
129
+
130
+ def t1_signed(trial):
131
+ torch.manual_seed(2000 + trial)
132
+ return [torch.randn(3, 64, 11, 17)]
133
+
134
+ def t2_misaligned(trial):
135
+ torch.manual_seed(3000 + trial)
136
+ return [torch.rand(2, 64, 13, 19)]
137
+
138
+ def t3_positive_spikes(trial):
139
+ torch.manual_seed(4000 + trial)
140
+ x = torch.rand(2, 64, 12, 18)
141
+ x[:, :, 0, 0] = 10.0
142
+ x[:, :, -1, -1] = 20.0
143
+ x[:, :, 5, 9] = 5.0
144
+ return [x]
145
+
146
+ def t4_positive_multiscale_grid(trial):
147
+ torch.manual_seed(5000 + trial)
148
+ channel_scale = torch.logspace(-2, 2, 64).view(1, 64, 1, 1)
149
+ rows = torch.linspace(0.25, 1.75, 15).view(1, 1, 15, 1)
150
+ cols = torch.linspace(1.75, 0.25, 21).view(1, 1, 1, 21)
151
+ x = (0.75 + 0.5 * torch.rand(1, 64, 15, 21))
152
+ return [x * channel_scale * rows * cols]
153
+
154
+ def t5_positive_alternating_regimes(trial):
155
+ torch.manual_seed(6000 + trial)
156
+ x = 0.02 + 0.01 * torch.rand(1, 64, 17, 23)
157
+ x[:, 0::2, 0::2, 0::2] = 24.0
158
+ x[:, 1::2, 1::2, 1::2] = 96.0
159
+ x[:, :, -1, -1] = torch.linspace(0.01, 128.0, 64)
160
+ return [x]
161
+
162
+ def t6_positive_sparse_saturation(trial):
163
+ torch.manual_seed(7000 + trial)
164
+ x = torch.full((1, 64, 19, 25), 1e-3)
165
+ x[:, :, 0, 0] = 192.0
166
+ x[:, :, -1, -1] = 256.0
167
+ x[:, 0::3, 9, 12] = 384.0
168
+ x[:, 1::3, 4::5, 6::7] = 64.0
169
+ return [x]
170
+
171
+ return [
172
+ ("T0_original", 5, t0_original),
173
+ ("T1_signed", 1, t1_signed),
174
+ ("T2_misaligned", 1, t2_misaligned),
175
+ ("T3_positive_spikes", 1, t3_positive_spikes),
176
+ ("T4_positive_multiscale_grid", 1, t4_positive_multiscale_grid),
177
+ ("T5_positive_alternating_regimes", 1, t5_positive_alternating_regimes),
178
+ ("T6_positive_sparse_saturation", 1, t6_positive_sparse_saturation),
179
+ ]
180
+
181
+ def probe(torch_module):
182
+ torch_module.manual_seed(0)
183
+ return [
184
+ ("p_aligned", [torch_module.rand(1, 64, 16, 32)]),
185
+ ("p_misaligned", [torch_module.randn(2, 64, 7, 11)]),
186
+ ]
187
+
188
+ K.PROBLEMS["L2p16_convtranspose2d_mish_a"] = dict(
189
+ kb_file="16_ConvTranspose2d_Mish_Add_Hardtanh_Scaling.py",
190
+ cuda=CUDA_SOURCE,
191
+ kernel_name="L2p16_convtranspose2d_mish_add_kernel",
192
+ ref=ref,
193
+ launch=launch,
194
+ suites=suites,
195
+ probe=probe,
196
+ )
substrates/candidate_L2p17_conv2d_instancenorm_di.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Mutation-friendly substrate for KernelBench level-2 problem 17."""
2
+
3
+
4
+ CUDA_SOURCE = r"""
5
+ #include <cuda_fp16.h>
6
+
7
+ __global__ void L2p17_conv2d_instancenorm_divide_kernel(
8
+ const float* x, float* out, const float* weight, const float* bias,
9
+ int batches, int input_height, int input_width,
10
+ int output_height, int output_width) {
11
+ int tid = threadIdx.x;
12
+ int instance_channel = blockIdx.x;
13
+ int output_channel = instance_channel % 128;
14
+ int batch = instance_channel / 128;
15
+ if (batch >= batches) return;
16
+
17
+ long long output_spatial = (long long)output_height * output_width;
18
+ long long output_base =
19
+ ((long long)batch * 128 + output_channel) * output_spatial;
20
+ __shared__ float partial[256];
21
+
22
+ // Conv2d defaults baked in from get_init_inputs(): stride=1, padding=0,
23
+ // dilation=1, groups=1, and bias=True. Weights are [Cout,Cin,Kh,Kw].
24
+ float local_sum = 0.0f;
25
+ for (long long spatial = tid; spatial < output_spatial;
26
+ spatial += blockDim.x) {
27
+ int output_y = (int)(spatial / output_width);
28
+ int output_x = (int)(spatial - (long long)output_y * output_width);
29
+ float value = bias[output_channel];
30
+ for (int input_channel = 0; input_channel < 64; input_channel++) {
31
+ for (int kernel_y = 0; kernel_y < 3; kernel_y++) {
32
+ int input_y = output_y + kernel_y;
33
+ for (int kernel_x = 0; kernel_x < 3; kernel_x++) {
34
+ int input_x = output_x + kernel_x;
35
+ long long input_index =
36
+ (((long long)batch * 64 + input_channel) * input_height
37
+ + input_y) * input_width + input_x;
38
+ long long weight_index =
39
+ (((long long)output_channel * 64 + input_channel) * 3
40
+ + kernel_y) * 3 + kernel_x;
41
+ value += x[input_index] * weight[weight_index];
42
+ }
43
+ }
44
+ }
45
+ out[output_base + spatial] = value;
46
+ local_sum += value;
47
+ }
48
+
49
+ partial[tid] = local_sum;
50
+ __syncthreads(); // sync-after-mean-partials
51
+ for (int width = 128; width > 0; width >>= 1) {
52
+ if (tid < width) { partial[tid] += partial[tid + width]; }
53
+ __syncthreads(); // sync-during-mean-reduction
54
+ }
55
+ float mean = partial[0] / (float)output_spatial;
56
+ __syncthreads(); // sync-after-mean-read
57
+
58
+ // InstanceNorm2d uses the biased population variance over H and W,
59
+ // independently for every (batch, channel) pair.
60
+ float local_squared_deviation = 0.0f;
61
+ for (long long spatial = tid; spatial < output_spatial;
62
+ spatial += blockDim.x) {
63
+ float centered = out[output_base + spatial] - mean;
64
+ local_squared_deviation += centered * centered;
65
+ }
66
+ partial[tid] = local_squared_deviation;
67
+ __syncthreads(); // sync-after-variance-partials
68
+ for (int width = 128; width > 0; width >>= 1) {
69
+ if (tid < width) { partial[tid] += partial[tid + width]; }
70
+ __syncthreads(); // sync-during-variance-reduction
71
+ }
72
+ float variance = partial[0] / (float)output_spatial;
73
+ float inverse_standard_deviation = rsqrtf(variance + 1.0e-5f);
74
+
75
+ for (long long spatial = tid; spatial < output_spatial;
76
+ spatial += blockDim.x) {
77
+ float normalized =
78
+ (out[output_base + spatial] - mean) * inverse_standard_deviation;
79
+ out[output_base + spatial] = normalized / 2.0f;
80
+ }
81
+ }
82
+ """
83
+
84
+
85
+ def register(K, torch, ctypes):
86
+ # The convolution parameters are model state, not get_inputs() values.
87
+ # Freeze one ordinary default initialization without disturbing caller RNG,
88
+ # and use the identical tensors in the reference and raw CUDA kernel.
89
+ with torch.random.fork_rng(devices=[]):
90
+ torch.manual_seed(0)
91
+ convolution = torch.nn.Conv2d(64, 128, 3)
92
+ frozen_weight = convolution.weight.detach().cpu().contiguous()
93
+ frozen_bias = convolution.bias.detach().cpu().contiguous()
94
+
95
+ device_parameters = {}
96
+
97
+ def parameters_for(x):
98
+ key = (x.device.type, x.device.index, x.dtype)
99
+ parameters = device_parameters.get(key)
100
+ if parameters is None:
101
+ parameters = (
102
+ frozen_weight.to(device=x.device, dtype=x.dtype),
103
+ frozen_bias.to(device=x.device, dtype=x.dtype),
104
+ )
105
+ device_parameters[key] = parameters
106
+ return parameters
107
+
108
+ def ref(x):
109
+ weight, bias = parameters_for(x)
110
+ value = torch.nn.functional.conv2d(
111
+ x, weight, bias=bias, stride=1, padding=0,
112
+ dilation=1, groups=1,
113
+ )
114
+ value = torch.nn.functional.instance_norm(
115
+ value, running_mean=None, running_var=None,
116
+ weight=None, bias=None, use_input_stats=True,
117
+ momentum=0.1, eps=1.0e-5,
118
+ )
119
+ return value / 2.0
120
+
121
+ def launch(inputs, torch_module):
122
+ x = inputs[0]
123
+ batches, input_channels, input_height, input_width = x.shape
124
+ if input_channels != 64:
125
+ raise ValueError("level-2 problem 17 requires 64 input channels")
126
+ if input_height < 3 or input_width < 3:
127
+ raise ValueError("the 3x3 convolution requires spatial dimensions >= 3")
128
+
129
+ output_height = input_height - 2
130
+ output_width = input_width - 2
131
+ out = torch_module.empty(
132
+ (batches, 128, output_height, output_width),
133
+ device=x.device, dtype=x.dtype,
134
+ )
135
+ weight, bias = parameters_for(x)
136
+ out._substrate_keepalive = (weight, bias)
137
+ args = [
138
+ (ctypes.c_void_p, weight.data_ptr()),
139
+ (ctypes.c_void_p, bias.data_ptr()),
140
+ (ctypes.c_int, batches),
141
+ (ctypes.c_int, input_height),
142
+ (ctypes.c_int, input_width),
143
+ (ctypes.c_int, output_height),
144
+ (ctypes.c_int, output_width),
145
+ ]
146
+ return out, (batches * 128, 1, 1), (256, 1, 1), args
147
+
148
+ def suites():
149
+ def t0_original(trial):
150
+ torch.manual_seed(1000 + trial)
151
+ return [torch.rand(128, 64, 128, 128)]
152
+
153
+ def t1_signed(trial):
154
+ torch.manual_seed(2000 + trial)
155
+ return [torch.randn(3, 64, 11, 17)]
156
+
157
+ def t2_misaligned(trial):
158
+ torch.manual_seed(3000 + trial)
159
+ return [torch.rand(2, 64, 13, 19)]
160
+
161
+ def t3_positive_spikes(trial):
162
+ torch.manual_seed(4000 + trial)
163
+ x = torch.rand(2, 64, 12, 18)
164
+ x[:, :, 0, 0] = 10.0
165
+ x[:, :, -1, -1] = 20.0
166
+ x[:, :, 5, 9] = 5.0
167
+ return [x]
168
+
169
+ def t4_zero_variance_constant(trial):
170
+ torch.manual_seed(5000 + trial)
171
+ return [torch.full((1, 64, 7, 11), 3.0)]
172
+
173
+ def t5_fp16_overflow_constant(trial):
174
+ torch.manual_seed(6000 + trial)
175
+ return [torch.full((1, 64, 18, 18), 100000.0)]
176
+
177
+ def t6_misaligned_alternating_spikes(trial):
178
+ torch.manual_seed(7000 + trial)
179
+ height, width = 19, 21
180
+ spatial = torch.arange(height * width).reshape(height, width)
181
+ pattern = torch.where(
182
+ spatial.remainder(2) == 0,
183
+ torch.tensor(1.0e-3),
184
+ torch.tensor(3000.0),
185
+ )
186
+ pattern[0, 0] = 6000.0
187
+ pattern[-1, -1] = 9000.0
188
+ return [pattern.expand(2, 64, height, width).clone()]
189
+
190
+ return [
191
+ ("T0_original", 5, t0_original),
192
+ ("T1_signed", 1, t1_signed),
193
+ ("T2_misaligned", 1, t2_misaligned),
194
+ ("T3_positive_spikes", 1, t3_positive_spikes),
195
+ ("T4_zero_variance_constant", 1, t4_zero_variance_constant),
196
+ ("T5_fp16_overflow_constant", 1, t5_fp16_overflow_constant),
197
+ ("T6_misaligned_alternating_spikes", 1, t6_misaligned_alternating_spikes),
198
+ ]
199
+
200
+ def probe(torch_module):
201
+ torch_module.manual_seed(0)
202
+ return [
203
+ ("p_aligned", [torch_module.rand(1, 64, 16, 16)]),
204
+ ("p_misaligned", [torch_module.randn(2, 64, 7, 11)]),
205
+ ]
206
+
207
+ K.PROBLEMS["L2p17_conv2d_instancenorm_di"] = dict(
208
+ kb_file="17_Conv2d_InstanceNorm_Divide.py",
209
+ cuda=CUDA_SOURCE,
210
+ kernel_name="L2p17_conv2d_instancenorm_divide_kernel",
211
+ ref=ref,
212
+ launch=launch,
213
+ suites=suites,
214
+ probe=probe,
215
+ )
substrates/candidate_L2p18_matmul_sum_max_avgpool.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Mutation-friendly substrate for KernelBench level2 problem 18."""
2
+
3
+
4
+ CUDA_SOURCE = r"""
5
+ #include <cuda_fp16.h>
6
+
7
+ __global__ void matmul_sum_max_avgpool_kernel(
8
+ const float* x, float* out, const float* column_sums,
9
+ const float* bias_sum, int batch_size, int input_features) {
10
+ int batch = blockIdx.x;
11
+ int tid = threadIdx.x;
12
+ if (batch >= batch_size) return;
13
+
14
+ // Summing every output of nn.Linear gives
15
+ // sum_k x[k] * sum_j weight[j, k] + sum_j bias[j].
16
+ // Each thread scans a distinct strided subset of input features.
17
+ float local_sum = 0.0f;
18
+ for (int input_feature = tid;
19
+ input_feature < input_features;
20
+ input_feature += blockDim.x) {
21
+ long long input_index =
22
+ (long long)batch * input_features + input_feature;
23
+ local_sum += x[input_index] * column_sums[input_feature];
24
+ }
25
+
26
+ __shared__ float partial_sums[256];
27
+ partial_sums[tid] = local_sum;
28
+ __syncthreads(); // sync-after-partial-store
29
+
30
+ for (int width = 128; width > 0; width >>= 1) {
31
+ if (tid < width) {
32
+ partial_sums[tid] =
33
+ partial_sums[tid] + partial_sums[tid + width];
34
+ }
35
+ __syncthreads(); // sync-after-reduction-step
36
+ }
37
+
38
+ if (tid == 0) {
39
+ float linear_sum = partial_sums[0] + bias_sum[0];
40
+
41
+ // The remaining reductions all operate on a dimension of length one:
42
+ // max, mean, and logsumexp(singleton) each preserve linear_sum.
43
+ float maximum = linear_sum;
44
+ float average = maximum;
45
+ float first_logsumexp = average;
46
+ float second_logsumexp = first_logsumexp;
47
+ out[batch] = second_logsumexp;
48
+ }
49
+ }
50
+ """
51
+
52
+
53
+ def register(K, torch, ctypes):
54
+ input_features = 8192
55
+ output_features = 8192
56
+
57
+ # KernelBench constructs nn.Linear(8192, 8192) with its ordinary default
58
+ # initialization. Freeze one reproducible realization without changing the
59
+ # suite builder's RNG stream, and share it between ref and launch.
60
+ with torch.random.fork_rng(devices=[]):
61
+ torch.manual_seed(0)
62
+ linear = torch.nn.Linear(input_features, output_features, bias=True)
63
+ frozen_weight = linear.weight.detach().cpu().contiguous()
64
+ frozen_bias = linear.bias.detach().cpu().contiguous()
65
+
66
+ device_parameters = {}
67
+
68
+ def parameters_for(x):
69
+ key = (x.device.type, x.device.index, x.dtype)
70
+ parameters = device_parameters.get(key)
71
+ if parameters is None:
72
+ weight = frozen_weight.to(device=x.device, dtype=x.dtype)
73
+ bias = frozen_bias.to(device=x.device, dtype=x.dtype)
74
+ column_sums = weight.sum(dim=0).contiguous()
75
+ bias_sum = bias.sum().reshape(1).contiguous()
76
+ parameters = (weight, bias, column_sums, bias_sum)
77
+ device_parameters[key] = parameters
78
+ return parameters
79
+
80
+ def ref(x):
81
+ weight, bias, _, _ = parameters_for(x)
82
+ value = torch.nn.functional.linear(x, weight, bias)
83
+ value = torch.sum(value, dim=1, keepdim=True)
84
+ value = torch.max(value, dim=1, keepdim=True)[0]
85
+ value = torch.mean(value, dim=1, keepdim=True)
86
+ value = torch.logsumexp(value, dim=1, keepdim=True)
87
+ value = torch.logsumexp(value, dim=1, keepdim=True)
88
+ return value
89
+
90
+ def launch(inputs, torch_module):
91
+ x = inputs[0]
92
+ if x.ndim != 2 or x.shape[1] != input_features:
93
+ raise ValueError("expected input shape (batch_size, 8192)")
94
+
95
+ batch_size = x.shape[0]
96
+ _, _, column_sums, bias_sum = parameters_for(x)
97
+ out = torch_module.empty(
98
+ (batch_size, 1), device=x.device, dtype=x.dtype
99
+ )
100
+ args = [
101
+ (ctypes.c_void_p, column_sums.data_ptr()),
102
+ (ctypes.c_void_p, bias_sum.data_ptr()),
103
+ (ctypes.c_int, batch_size),
104
+ (ctypes.c_int, input_features),
105
+ ]
106
+ return out, (batch_size, 1, 1), (256, 1, 1), args
107
+
108
+ def suites():
109
+ frozen_column_sums = frozen_weight.sum(dim=0)
110
+ strongest_positive = int(torch.argmax(frozen_column_sums).item())
111
+ positive_columns = frozen_column_sums > 0
112
+
113
+ def t0_original(trial):
114
+ torch.manual_seed(1000 + trial)
115
+ return [torch.rand(1024, 8192)]
116
+
117
+ def t1_signed(trial):
118
+ torch.manual_seed(2000 + trial)
119
+ return [torch.randn(11, 8192) * 0.05]
120
+
121
+ def t2_misaligned_batch(trial):
122
+ torch.manual_seed(3000 + trial)
123
+ return [torch.rand(37, 8192)]
124
+
125
+ def t3_positive_tail_spike(trial):
126
+ torch.manual_seed(4000 + trial)
127
+ x = torch.rand(7, 8192)
128
+ x[:, -1] = 50.0
129
+ x[-1, -31:] = 25.0
130
+ return [x]
131
+
132
+ def t4_positive_single_column_overflow(trial):
133
+ torch.manual_seed(5000 + trial)
134
+ x = torch.zeros(3, 8192)
135
+ x[:, strongest_positive] = 50000.0
136
+ return [x]
137
+
138
+ def t5_positive_coefficient_pattern(trial):
139
+ torch.manual_seed(6000 + trial)
140
+ x = torch.full((5, 8192), 1.0e-3)
141
+ x[:, positive_columns] = 128.0
142
+ return [x]
143
+
144
+ return [
145
+ ("T0_original", 5, t0_original),
146
+ ("T1_signed", 1, t1_signed),
147
+ ("T2_misaligned_batch", 1, t2_misaligned_batch),
148
+ ("T3_positive_tail_spike", 1, t3_positive_tail_spike),
149
+ ("T4_positive_single_column_overflow", 1,
150
+ t4_positive_single_column_overflow),
151
+ ("T5_positive_coefficient_pattern", 1,
152
+ t5_positive_coefficient_pattern),
153
+ ]
154
+
155
+ def probe(torch_module):
156
+ torch_module.manual_seed(0)
157
+ return [
158
+ ("p_aligned", [torch_module.rand(16, 8192)]),
159
+ ("p_misaligned", [torch_module.randn(3, 8192) * 0.05]),
160
+ ]
161
+
162
+ K.PROBLEMS["L2p18_matmul_sum_max_avgpool"] = dict(
163
+ kb_file="18_Matmul_Sum_Max_AvgPool_LogSumExp_LogSumExp.py",
164
+ cuda=CUDA_SOURCE,
165
+ kernel_name="matmul_sum_max_avgpool_kernel",
166
+ ref=ref,
167
+ launch=launch,
168
+ suites=suites,
169
+ probe=probe,
170
+ )