WIP: fix InstanceNorm large-mean cancellation; CUDA regeneration pending

#1
by Elfsong - opened
README.md CHANGED
@@ -19,6 +19,13 @@ GPU-Kernel Benchmark Oracles*: the mutation operators, the verified CUDA
19
  substrates they mutate, the kill witnesses, and the pipeline that produced
20
  every number in the paper.
21
 
 
 
 
 
 
 
 
22
  ## Layout
23
 
24
  ```
 
19
  substrates they mutate, the kill witnesses, and the pipeline that produced
20
  every number in the paper.
21
 
22
+ **InstanceNorm repair pending CUDA verification:** this branch changes the
23
+ InstanceNorm substrate to two-pass variance and adds shifted-input suites.
24
+ Its existing `witnesses/instancenorm.json` and `summary.json` entry are historical
25
+ records for revision `d04d6fc`, not measurements of the modified source. Do not
26
+ merge or use them as current repair results until the GPU regeneration completes.
27
+ See [repair status and reproduction](repairs/instancenorm/README.md).
28
+
29
  ## Layout
30
 
31
  ```
pipeline/repair_instancenorm.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Verify and regenerate only InstanceNorm, with fresh, source-bound journals.
2
+
3
+ Requires NVIDIA CUDA 12.x, PyTorch and at least 40 GiB free GPU memory for the
4
+ unchanged official inputs and the screening pipeline's two-seed cache.
5
+ Run from any directory:
6
+ python pipeline/repair_instancenorm.py --run-dir /tmp/instancenorm-repair
7
+
8
+ Writes admission/precision evidence, screening and full-matrix journals,
9
+ witnesses and a per-problem summary. Does not modify published artifacts.
10
+ """
11
+ import argparse
12
+ import collections
13
+ import ctypes
14
+ import hashlib
15
+ import importlib.util
16
+ import json
17
+ import os
18
+ from pathlib import Path
19
+ import subprocess
20
+ import sys
21
+ import urllib.request
22
+
23
+ ROOT = Path(__file__).resolve().parents[1]
24
+ BASELINE_REVISION = "d04d6fc72504750804c4f4b45b4a8d7dc7c1880d"
25
+ BASELINE_SHA256 = "356b305c8038dea0244ad08100da0b650ffc1210c46edc7c891ca35017ae9fad"
26
+ PROBLEM = "instancenorm"
27
+ KEPT_CLASSES = {"killed_by_T0", "high_value", "no_witness"}
28
+
29
+
30
+ def fingerprint():
31
+ paths = [ROOT / "substrates/candidate_instancenorm.py",
32
+ ROOT / "pipeline/mutator.py", ROOT / "pipeline/nvrtc_tce.py",
33
+ ROOT / "pipeline/screen_mutants.py", ROOT / "pipeline/full_matrix.py",
34
+ ROOT / "pipeline/gate_candidates.py", ROOT / "pipeline/suite_filter.py",
35
+ ROOT / "pipeline/kernels_def.py", ROOT / "pipeline/problems_ext.py",
36
+ ROOT / "pipeline/candidates_loader.py",
37
+ Path(__file__).resolve(), *sorted((ROOT / "rules").glob("*.py"))]
38
+ return {str(p.relative_to(ROOT)): hashlib.sha256(p.read_bytes()).hexdigest()
39
+ for p in paths}
40
+
41
+
42
+ def write_json(path, value):
43
+ path.write_text(json.dumps(value, indent=2, sort_keys=True) + "\n")
44
+
45
+
46
+ def records(path):
47
+ return [json.loads(line) for line in path.read_text().splitlines() if line]
48
+
49
+
50
+ def export_records(screen, matrix):
51
+ """Promote matrix-only kills as well, so summary and witnesses agree."""
52
+ outcomes = {r["id"]: r for r in screen if r["type"] == "RESULT"}
53
+ witnesses = {}
54
+ for mid, r in outcomes.items():
55
+ if r["cls"] in KEPT_CLASSES:
56
+ witnesses[mid] = dict(rule=r["rule"], family=r["category"],
57
+ site=r["site"], cls=r["cls"],
58
+ killed_by_official=r["cls"] == "killed_by_T0",
59
+ witness=r.get("witness"))
60
+ for cell in matrix:
61
+ if cell["type"] == "CELL" and cell["outcome"] == "killed":
62
+ witness = witnesses[cell["id"]]
63
+ if witness["cls"] == "no_witness":
64
+ witness.update(cls="high_value", witness=cell["suite"])
65
+ summary = dict(mutants=len(witnesses),
66
+ witnessed=sum(r["cls"] != "no_witness" for r in witnesses.values()),
67
+ killed_by_official=sum(r["killed_by_official"] for r in witnesses.values()),
68
+ level=12)
69
+ return witnesses, summary
70
+
71
+
72
+ def validate_records(screen, matrix, generated_ids, suite_names):
73
+ outcomes = {r["id"]: r for r in screen if r["type"] == "RESULT"}
74
+ if set(outcomes) != set(generated_ids):
75
+ raise RuntimeError("Screening results do not cover exactly the current mutation source")
76
+ cells = {(r["id"], r["suite"]) for r in matrix if r["type"] == "CELL"}
77
+ crash_reasons = {"crash", "probe_crash", "cuda_poisoned"}
78
+ expected = {(mid, suite) for mid, r in outcomes.items()
79
+ if r["cls"] in KEPT_CLASSES and r.get("reason") not in crash_reasons
80
+ for suite in suite_names}
81
+ if cells != expected:
82
+ raise RuntimeError("Full matrix is missing cells or contains stale/unknown cells")
83
+
84
+
85
+ def check_infrastructure_failure(log, rows, returncode):
86
+ details = log.lower() + "\n" + "\n".join(str(r.get("detail", "")).lower() for r in rows)
87
+ memory_errors = ["out of memory", "out_of_memory", "alloc_failed", "std::bad_alloc",
88
+ "can't allocate memory", "cannot allocate memory"]
89
+ if returncode in [-9, 137] or any(error in details for error in memory_errors):
90
+ raise RuntimeError("Infrastructure failure, cannot count mutant kills")
91
+
92
+
93
+ def load_runtime(run_dir):
94
+ # The released artifact keeps rules and substrates alongside pipeline/.
95
+ # Load this candidate directly, without moving any source into accepted/.
96
+ sys.path[:0] = [str(ROOT), str(ROOT / "pipeline")]
97
+ import torch
98
+ import kernels_def as K
99
+ import screen_mutants as screen
100
+ import full_matrix as matrix
101
+ import suite_filter
102
+ import mutator
103
+ if len(mutator.RULES) != 124:
104
+ raise RuntimeError("Expected all 124 published mutation rules to be loaded")
105
+ spec = importlib.util.spec_from_file_location(
106
+ "repair_candidate", ROOT / "substrates/candidate_instancenorm.py")
107
+ candidate = importlib.util.module_from_spec(spec)
108
+ spec.loader.exec_module(candidate)
109
+ candidate.register(K, torch, ctypes)
110
+ screen.RESULTS = matrix.RESULTS = str(run_dir)
111
+ suite_filter._cache = {} # all six suites must pass admission first
112
+ capability = torch.cuda.get_device_capability()
113
+ os.environ["NVRTC_ARCH"] = f"compute_{capability[0]}{capability[1]}"
114
+ return torch, K, screen, matrix
115
+
116
+
117
+ def verify(run_dir):
118
+ torch, K, screen, _ = load_runtime(run_dir)
119
+ from nvrtc_tce import compile_ptx, externc, device_source
120
+ import gate_candidates
121
+ free, total = torch.cuda.mem_get_info()
122
+ if free < 40 * 1024**3:
123
+ raise RuntimeError("Official-input screening requires at least 40 GiB free GPU memory")
124
+ admitted, detail = gate_candidates.check(PROBLEM)
125
+ if not admitted:
126
+ raise RuntimeError(f"Fixed substrate failed admission: {detail}")
127
+ report = dict(admitted=True, detail=detail, baseline_revision=BASELINE_REVISION,
128
+ gpu=torch.cuda.get_device_name(), torch=torch.__version__,
129
+ cuda=torch.version.cuda, free_gpu_bytes=free, total_gpu_bytes=total,
130
+ source_hashes=fingerprint(), runs=[])
131
+ url = ("https://huggingface.co/datasets/Elfsong/KernelBench-M/resolve/"
132
+ f"{BASELINE_REVISION}/substrates/candidate_instancenorm.py")
133
+ with urllib.request.urlopen(url, timeout=60) as response:
134
+ baseline_bytes = response.read()
135
+ if hashlib.sha256(baseline_bytes).hexdigest() != BASELINE_SHA256:
136
+ raise RuntimeError("Baseline source checksum mismatch")
137
+ baseline = baseline_bytes.decode().split('CUDA_SOURCE = r"""', 1)[1].split('"""', 1)[0]
138
+ cuda_lib = ctypes.CDLL("libcuda.so.1")
139
+ kernels = {}
140
+ for label, source in [("baseline", baseline), ("fixed", K.PROBLEMS[PROBLEM]["cuda"])]:
141
+ image = compile_ptx(externc(device_source(source)), f"{label}.cu")
142
+ kernels[label] = screen.NvrtcKernel(cuda_lib, image, "instancenorm_kernel")
143
+ try:
144
+ for offset in [0, 10, 100, 1000, -1000]:
145
+ torch.manual_seed(0)
146
+ x = (torch.randn(8, 64, 128, 128) + offset).cuda()
147
+ with torch.no_grad():
148
+ truth = torch.nn.functional.instance_norm(x.double(), eps=1e-5)
149
+ reference = K.PROBLEMS[PROBLEM]["ref"](x)
150
+ row = {"offset": offset, "torch_fp32_max_abs_error":
151
+ float((reference.double() - truth).abs().max())}
152
+ for label, kernel in kernels.items():
153
+ out = kernel.launch(PROBLEM, [x], torch)
154
+ error = float((out.double() - truth).abs().max())
155
+ row[label + "_max_abs_error"] = error
156
+ if label == "fixed":
157
+ if not torch.isfinite(out).all() or error >= 1e-3:
158
+ raise RuntimeError(f"Fixed precision regression failed: {row}")
159
+ if screen.compare(reference, out, torch) != "survived":
160
+ raise RuntimeError(f"Fixed benchmark comparison failed: {row}")
161
+ del out
162
+ report["runs"].append(row)
163
+ print(json.dumps(row), flush=True)
164
+ del x, truth, reference
165
+ torch.cuda.empty_cache()
166
+ finally:
167
+ for kernel in kernels.values():
168
+ kernel.unload()
169
+ shifted = [r for r in report["runs"] if abs(r["offset"]) == 1000]
170
+ if not any(r["baseline_max_abs_error"] > 1e-2 for r in shifted):
171
+ raise RuntimeError("Original precision failure was not reproduced on this GPU")
172
+ write_json(run_dir / "verification.json", report)
173
+
174
+
175
+ def run_phase(phase, run_dir):
176
+ torch, K, screen, matrix = load_runtime(run_dir)
177
+ functions = {"probe": screen.probe, "screen": screen.worker, "matrix": matrix.worker}
178
+ functions[phase](PROBLEM)
179
+
180
+
181
+ def main():
182
+ parser = argparse.ArgumentParser(description=__doc__)
183
+ parser.add_argument("--run-dir", required=True, type=Path)
184
+ parser.add_argument("--worker", choices=["verify", "probe", "screen", "matrix"])
185
+ args = parser.parse_args()
186
+ os.environ["MUTANT_CAP"] = "0"
187
+ run_dir = args.run_dir.resolve()
188
+ if args.worker:
189
+ if args.worker == "verify":
190
+ verify(run_dir)
191
+ else:
192
+ run_phase(args.worker, run_dir)
193
+ return
194
+ if run_dir.exists():
195
+ raise RuntimeError("Use a NEW run directory; never reuse old mutation journals")
196
+ run_dir.mkdir(parents=True)
197
+ write_json(run_dir / "manifest.json", dict(source_hashes=fingerprint(),
198
+ baseline_revision=BASELINE_REVISION,
199
+ status="running"))
200
+ command = [sys.executable, str(Path(__file__).resolve()), "--run-dir", str(run_dir)]
201
+ subprocess.run(command + ["--worker", "verify"], check=True, timeout=900)
202
+ for phase, filename, marker in [("probe", "screen_instancenorm.jsonl", "PROBE_DONE"),
203
+ ("screen", "screen_instancenorm.jsonl", "DONE"),
204
+ ("matrix", "matrix_instancenorm.jsonl", "MDONE")]:
205
+ journal = run_dir / filename
206
+ for attempt in range(120):
207
+ previous = journal.stat().st_size if journal.exists() else 0
208
+ log_path = run_dir / f"{phase}-{attempt}.log"
209
+ with log_path.open("w") as log:
210
+ result = subprocess.run(command + ["--worker", phase], stdout=log,
211
+ stderr=subprocess.STDOUT, timeout=1800)
212
+ log_text = log_path.read_text()
213
+ rows = records(journal) if journal.exists() else []
214
+ check_infrastructure_failure(log_text, rows, result.returncode)
215
+ if result.returncode == 0 and any(r["type"] == marker for r in rows):
216
+ break
217
+ if not journal.exists() or journal.stat().st_size <= previous:
218
+ raise RuntimeError(f"No journal progress; inspect {log_path}")
219
+ print(f"{phase}: recovering after mutant crash, attempt {attempt + 1}", flush=True)
220
+ else:
221
+ raise RuntimeError(f"{phase} did not finish")
222
+ if json.loads((run_dir / "manifest.json").read_text())["source_hashes"] != fingerprint():
223
+ raise RuntimeError("Source changed during measurement")
224
+ screen_rows = records(run_dir / "screen_instancenorm.jsonl")
225
+ matrix_rows = records(run_dir / "matrix_instancenorm.jsonl")
226
+ _, K, _, _ = load_runtime(run_dir)
227
+ import mutator
228
+ from nvrtc_tce import device_source
229
+ generated = list(mutator.generate(PROBLEM, device_source(K.PROBLEMS[PROBLEM]["cuda"])))
230
+ validate_records(screen_rows, matrix_rows, {r["id"] for r in generated},
231
+ {n for n, _, _ in K.PROBLEMS[PROBLEM]["suites"]() if n != "T0_original"})
232
+ witnesses, summary = export_records(screen_rows, matrix_rows)
233
+ write_json(run_dir / "instancenorm.json", witnesses)
234
+ write_json(run_dir / "summary_instancenorm.json", summary)
235
+ manifest = json.loads((run_dir / "manifest.json").read_text())
236
+ manifest.update(status="complete", summary=summary,
237
+ classifications=dict(collections.Counter(
238
+ r["cls"] for r in screen_rows if r["type"] == "RESULT")))
239
+ write_json(run_dir / "manifest.json", manifest)
240
+ print(json.dumps(manifest, indent=2), flush=True)
241
+
242
+
243
+ if __name__ == "__main__":
244
+ main()
repairs/instancenorm/README.md ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # InstanceNorm cancellation repair — CUDA validation pending
2
+
3
+ The central correctness finding in Jayden Vasquez's report is valid:
4
+ `E[x^2] - mean^2` in fp32 loses precision when the input mean is large relative
5
+ to its standard deviation. The fixed substrate computes the mean first, then
6
+ reduces squared centered differences. The reference, launch geometry, original
7
+ inputs, epsilon and benchmark comparison tolerance are unchanged.
8
+
9
+ Source report: [reproduction](https://gist.github.com/jayden1711/b9c73089192deb6bc34e8b68318dfc78)
10
+ and [proposed patch](https://gist.github.com/jayden1711/f9399cb65a1abfd9145ff6e40baaba0b).
11
+ The variance change follows the proposed patch; this repair also adds positive
12
+ and negative shifted-input suites and a fresh measurement/export entry point.
13
+
14
+ ## Independently checked
15
+
16
+ Baseline: `d04d6fc72504750804c4f4b45b4a8d7dc7c1880d`. Its InstanceNorm source
17
+ matches the local baseline byte-for-byte.
18
+
19
+ The CPU regression compiles and runs the actual `CUDA_SOURCE` body, using
20
+ 256 CPU threads with shared arrays and barriers. It compares the output with a
21
+ float64 calculation on the same fp32 input values. This is a numerical check,
22
+ not CUDA execution or a GPU race/performance check.
23
+
24
+ | Input | Baseline max absolute error | Fixed max absolute error |
25
+ | --- | ---: | ---: |
26
+ | Normal noise + 1000, 2 planes of 128 × 128 | 0.160885 | 0.000029383 |
27
+ | Normal noise - 1000, 2 planes of 37 × 43 | 0.221997 | 0.000059989 |
28
+ | Zero-centered noise, 2 planes of 37 × 43 | 0.000000297 | 0.000000297 |
29
+ | Constant 1000, 2 planes of 17 × 19 | 0 | 0 |
30
+
31
+ The old source fails both shifted regressions at a 1e-3 max-absolute-error
32
+ threshold. The fixed source passes all four. Exact inputs, environment and
33
+ source hashes are recorded in [cpu_results.json](cpu_results.json).
34
+
35
+ Run the local numerical and export checks with NumPy and a C++17 compiler:
36
+
37
+ ```bash
38
+ python -m unittest discover -s tests -v
39
+ ```
40
+
41
+ The report's description of all existing suite means as near zero is imprecise:
42
+ T0/T2 use uniform positive inputs and T3 includes positive spikes. The meaningful
43
+ coverage gap is large absolute means with small within-plane variation.
44
+
45
+ The reporter's exact RTX 5080 errors, two-pass GPU error and 1.33× timing ratio
46
+ have not been independently reproduced. Nor does this check establish the
47
+ correctness of other normalization substrates. Several fused substrates also
48
+ contain raw-second-moment variance expressions and require separate analysis.
49
+
50
+ ## Mutation measurements must be regenerated
51
+
52
+ All 124 published rules load in the repair runner. They generate 67 syntactic
53
+ mutation candidates from the old source and 84 from the changed source, before
54
+ compilation and equivalence filtering. The published 66 records describe the
55
+ old filtered pool. Even reused mutation IDs must not inherit old classifications
56
+ because the underlying source has changed.
57
+
58
+ The baseline summary reports 64 witnessed mutants, while its witness JSON
59
+ contains 48 official kills, 9 targeted kills and 9 no-witness entries. Full-matrix
60
+ discoveries might explain that difference; the original raw matrix is not part
61
+ of the release. The new exporter promotes matrix-only kills to explicit witnesses
62
+ and calculates its summary from those exported records.
63
+
64
+ On an NVIDIA GPU with CUDA 12.x, PyTorch and at least 40 GiB free device memory:
65
+
66
+ ```bash
67
+ python pipeline/repair_instancenorm.py --run-dir /tmp/instancenorm-repair
68
+ ```
69
+
70
+ Use a new directory each time. The runner loads this substrate directly despite
71
+ the release's flattened substrate layout, checks all six suites against the
72
+ unchanged reference, compares baseline/fixed outputs with float64 at offsets
73
+ 0, 10, 100, 1000 and -1000, then performs fresh probe, screening and full-matrix
74
+ passes. It uses the published compiler and crash-isolation pipeline and records
75
+ the GPU, software versions and source hashes. Infrastructure allocation failures
76
+ abort the run instead of being counted as mutant kills.
77
+
78
+ Only after `manifest.json` says `complete` and the source hashes match should
79
+ the generated `instancenorm.json`, `summary_instancenorm.json`,
80
+ `verification.json` and raw journals be incorporated into the release. Update
81
+ only the InstanceNorm entry of `summary.json` and preserve all other problems.
82
+ Publish its new admission evidence alongside those measurements in one commit.
83
+
84
+ Until then, this is a repair proposal: existing witnesses, admission reports and
85
+ summary entries still describe the baseline. Global paper aggregates, including
86
+ holdout and ladder results, are also baseline snapshots and must remain labeled
87
+ as such unless those analyses are rerun. No GPU validation or new witness
88
+ classification is claimed by this branch.
repairs/instancenorm/cpu_results.json ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "method": "Actual CUDA_SOURCE compiled with C++17; __shared__ arrays shared among 256 CPU threads, __syncthreads mapped to a barrier. Not CUDA execution.",
3
+ "environment": "macOS-26.6.2-arm64-arm-64bit",
4
+ "numpy": "2.0.2",
5
+ "max_abs_error_threshold": 0.001,
6
+ "baseline_revision": "d04d6fc72504750804c4f4b45b4a8d7dc7c1880d",
7
+ "results": {
8
+ "baseline": {
9
+ "source_sha256": "356b305c8038dea0244ad08100da0b650ffc1210c46edc7c891ca35017ae9fad",
10
+ "cases": {
11
+ "large_positive_mean": {
12
+ "shape": [
13
+ 2,
14
+ 128,
15
+ 128
16
+ ],
17
+ "max_abs_error": 0.1608845495314628,
18
+ "passed": false
19
+ },
20
+ "large_negative_mean_odd_spatial_size": {
21
+ "shape": [
22
+ 2,
23
+ 37,
24
+ 43
25
+ ],
26
+ "max_abs_error": 0.22199731572928982,
27
+ "passed": false
28
+ },
29
+ "zero_centered": {
30
+ "shape": [
31
+ 2,
32
+ 37,
33
+ 43
34
+ ],
35
+ "max_abs_error": 2.96955678713573e-07,
36
+ "passed": true
37
+ },
38
+ "constant_planes": {
39
+ "shape": [
40
+ 2,
41
+ 17,
42
+ 19
43
+ ],
44
+ "max_abs_error": 0.0,
45
+ "passed": true
46
+ }
47
+ }
48
+ },
49
+ "fixed": {
50
+ "source_sha256": "4829cad8728bcc1c99c582fb1da28bc6aa3e2a83f845ae7d7c4c520b2eab6d52",
51
+ "cases": {
52
+ "large_positive_mean": {
53
+ "shape": [
54
+ 2,
55
+ 128,
56
+ 128
57
+ ],
58
+ "max_abs_error": 2.9382815827982967e-05,
59
+ "passed": true
60
+ },
61
+ "large_negative_mean_odd_spatial_size": {
62
+ "shape": [
63
+ 2,
64
+ 37,
65
+ 43
66
+ ],
67
+ "max_abs_error": 5.998870941592571e-05,
68
+ "passed": true
69
+ },
70
+ "zero_centered": {
71
+ "shape": [
72
+ 2,
73
+ 37,
74
+ 43
75
+ ],
76
+ "max_abs_error": 2.96955678713573e-07,
77
+ "passed": true
78
+ },
79
+ "constant_planes": {
80
+ "shape": [
81
+ 2,
82
+ 17,
83
+ 19
84
+ ],
85
+ "max_abs_error": 0.0,
86
+ "passed": true
87
+ }
88
+ }
89
+ }
90
+ }
91
+ }
substrates/candidate_instancenorm.py CHANGED
@@ -19,23 +19,39 @@ __global__ void instancenorm_kernel(const float* x, float* out,
19
  if (offset < spatial) {
20
  float value = x[base + offset];
21
  local_sum += value;
22
- local_square_sum += value * value;
23
  }
24
  }
25
  sums[tid] = local_sum;
26
- square_sums[tid] = local_square_sum;
27
  __syncthreads(); // sync-after-partial-sums
28
 
29
  for (int stride = 128; stride > 0; stride >>= 1) {
30
  if (tid < stride) {
31
  sums[tid] += sums[tid + stride];
32
- square_sums[tid] += square_sums[tid + stride];
33
  }
34
  __syncthreads(); // sync-during-reduction
35
  }
36
 
37
  float mean = sums[0] / (float)spatial;
38
- float variance = square_sums[0] / (float)spatial - mean * mean;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  variance = fmaxf(variance, 0.0f);
40
  float inverse_std = rsqrtf(variance + 1.0e-5f);
41
  __syncthreads(); // sync-before-normalization
@@ -87,10 +103,20 @@ def register(K, torch, ctypes):
87
  x[:, :, -1, -1] = 50.0
88
  return [x]
89
 
 
 
 
 
 
 
 
 
90
  return [("T0_original", 5, t0_original),
91
  ("T1_signed", 2, t1_signed),
92
  ("T2_misaligned", 2, t2_misaligned),
93
- ("T3_spatial_spike", 1, t3_spatial_spike)]
 
 
94
 
95
  def probe(torch_module):
96
  torch_module.manual_seed(0)
 
19
  if (offset < spatial) {
20
  float value = x[base + offset];
21
  local_sum += value;
 
22
  }
23
  }
24
  sums[tid] = local_sum;
 
25
  __syncthreads(); // sync-after-partial-sums
26
 
27
  for (int stride = 128; stride > 0; stride >>= 1) {
28
  if (tid < stride) {
29
  sums[tid] += sums[tid + stride];
 
30
  }
31
  __syncthreads(); // sync-during-reduction
32
  }
33
 
34
  float mean = sums[0] / (float)spatial;
35
+
36
+ // Two-pass variance avoids cancellation when |mean| is much larger than std.
37
+ for (long long iteration = 0; iteration < iterations; iteration++) {
38
+ long long offset = iteration * 256 + tid;
39
+ if (offset < spatial) {
40
+ float centered = x[base + offset] - mean;
41
+ local_square_sum += centered * centered;
42
+ }
43
+ }
44
+ square_sums[tid] = local_square_sum;
45
+ __syncthreads(); // sync-after-partial-square-sums
46
+
47
+ for (int stride = 128; stride > 0; stride >>= 1) {
48
+ if (tid < stride) {
49
+ square_sums[tid] += square_sums[tid + stride];
50
+ }
51
+ __syncthreads(); // sync-during-square-reduction
52
+ }
53
+
54
+ float variance = square_sums[0] / (float)spatial;
55
  variance = fmaxf(variance, 0.0f);
56
  float inverse_std = rsqrtf(variance + 1.0e-5f);
57
  __syncthreads(); // sync-before-normalization
 
103
  x[:, :, -1, -1] = 50.0
104
  return [x]
105
 
106
+ def t4_large_positive_mean(t):
107
+ torch.manual_seed(5000 + t)
108
+ return [torch.randn(2, 4, 128, 128) + 1000.0]
109
+
110
+ def t5_large_negative_mean(t):
111
+ torch.manual_seed(6000 + t)
112
+ return [torch.randn(2, 3, 37, 43) - 1000.0]
113
+
114
  return [("T0_original", 5, t0_original),
115
  ("T1_signed", 2, t1_signed),
116
  ("T2_misaligned", 2, t2_misaligned),
117
+ ("T3_spatial_spike", 1, t3_spatial_spike),
118
+ ("T4_large_positive_mean", 2, t4_large_positive_mean),
119
+ ("T5_large_negative_mean", 2, t5_large_negative_mean)]
120
 
121
  def probe(torch_module):
122
  torch_module.manual_seed(0)
tests/instancenorm_cpu_harness.cpp ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Numerical regression harness only: executes one CUDA block at a time on CPU.
2
+ // This checks the actual kernel body, but cannot validate GPU race behavior,
3
+ // CUDA compilation, approximate rsqrt, or performance.
4
+ #include <cmath>
5
+ #include <condition_variable>
6
+ #include <cstdlib>
7
+ #include <iostream>
8
+ #include <mutex>
9
+ #include <thread>
10
+ #include <vector>
11
+
12
+ struct Dim { int x = 0; int y = 0; int z = 0; };
13
+ thread_local Dim blockIdx, threadIdx;
14
+
15
+ class BlockBarrier {
16
+ std::mutex mutex;
17
+ std::condition_variable ready;
18
+ int arrived = 0;
19
+ int generation = 0;
20
+ public:
21
+ void wait() {
22
+ std::unique_lock<std::mutex> lock(mutex);
23
+ int current = generation;
24
+ if (++arrived == 256) {
25
+ arrived = 0;
26
+ ++generation;
27
+ ready.notify_all();
28
+ } else {
29
+ ready.wait(lock, [&] { return generation != current; });
30
+ }
31
+ }
32
+ };
33
+ BlockBarrier barrier;
34
+ #define __global__
35
+ #define __shared__ static
36
+ #define __syncthreads() barrier.wait()
37
+ float rsqrtf(float x) { return 1.0f / std::sqrt(x); }
38
+
39
+ // KERNEL_BODY
40
+
41
+ int main(int argc, char** argv) {
42
+ if (argc != 4) return 2;
43
+ int planes = std::atoi(argv[1]);
44
+ int height = std::atoi(argv[2]);
45
+ int width = std::atoi(argv[3]);
46
+ size_t count = size_t(planes) * height * width;
47
+ std::vector<float> x(count), out(count, NAN);
48
+ std::cin.read(reinterpret_cast<char*>(x.data()), count * sizeof(float));
49
+ if (!std::cin) return 3;
50
+ std::vector<std::thread> workers;
51
+ for (int tid = 0; tid < 256; ++tid) {
52
+ workers.emplace_back([&, tid] {
53
+ threadIdx.x = tid;
54
+ for (int plane = 0; plane < planes; ++plane) {
55
+ blockIdx.x = plane;
56
+ instancenorm_kernel(x.data(), out.data(), planes, height, width);
57
+ barrier.wait();
58
+ }
59
+ });
60
+ }
61
+ for (auto& worker : workers) worker.join();
62
+ std::cout.write(reinterpret_cast<const char*>(out.data()), count * sizeof(float));
63
+ }
tests/test_instancenorm.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run the actual kernel arithmetic on CPU; real CUDA verification is separate.
2
+
3
+ Requires NumPy and a C++17 compiler. No PyTorch or NVIDIA GPU is needed.
4
+ """
5
+ import importlib.util
6
+ from pathlib import Path
7
+ import shutil
8
+ import subprocess
9
+ import tempfile
10
+ import unittest
11
+
12
+ import numpy as np
13
+
14
+ ARTIFACT = Path(__file__).resolve().parents[1]
15
+
16
+
17
+ class InstanceNormNumerics(unittest.TestCase):
18
+ @classmethod
19
+ def setUpClass(cls):
20
+ compiler = shutil.which("c++")
21
+ if compiler is None:
22
+ raise unittest.SkipTest("C++17 compiler required for CPU numerical harness")
23
+ spec = importlib.util.spec_from_file_location(
24
+ "candidate_instancenorm", ARTIFACT / "substrates/candidate_instancenorm.py")
25
+ module = importlib.util.module_from_spec(spec)
26
+ spec.loader.exec_module(module)
27
+ source = module.CUDA_SOURCE.replace("#include <cuda_fp16.h>", "")
28
+ harness = Path(__file__).with_name("instancenorm_cpu_harness.cpp").read_text()
29
+ cls.temp = tempfile.TemporaryDirectory()
30
+ cls.addClassCleanup(cls.temp.cleanup)
31
+ path = Path(cls.temp.name)
32
+ (path / "kernel.cpp").write_text(harness.replace("// KERNEL_BODY", source))
33
+ cls.binary = path / "kernel"
34
+ subprocess.run([compiler, "-std=c++17", "-O2", "-ffp-contract=fast", "-pthread",
35
+ str(path / "kernel.cpp"), "-o", str(cls.binary)], check=True,
36
+ capture_output=True)
37
+
38
+ def check_input(self, x):
39
+ planes, height, width = x.shape
40
+ result = subprocess.run([str(self.binary), str(planes), str(height), str(width)],
41
+ input=x.tobytes(), capture_output=True, check=True,
42
+ timeout=60)
43
+ actual = np.frombuffer(result.stdout, dtype=np.float32).reshape(x.shape)
44
+ double = x.astype(np.float64)
45
+ centered = double - double.mean(axis=(1, 2), keepdims=True)
46
+ expected = centered / np.sqrt(
47
+ (centered * centered).mean(axis=(1, 2), keepdims=True) + 1e-5)
48
+ error = float(np.max(np.abs(actual - expected)))
49
+ self.assertTrue(np.isfinite(actual).all())
50
+ self.assertLess(error, 1e-3, f"maximum error against float64: {error}")
51
+
52
+ def test_large_positive_mean(self):
53
+ x = np.random.default_rng(0).standard_normal((2, 128, 128), dtype=np.float32)
54
+ self.check_input(x + np.float32(1000))
55
+
56
+ def test_large_negative_mean_odd_spatial_size(self):
57
+ x = np.random.default_rng(1).standard_normal((2, 37, 43), dtype=np.float32)
58
+ self.check_input(x - np.float32(1000))
59
+
60
+ def test_zero_centered(self):
61
+ x = np.random.default_rng(2).standard_normal((2, 37, 43), dtype=np.float32)
62
+ self.check_input(x)
63
+
64
+ def test_constant_planes(self):
65
+ self.check_input(np.full((2, 17, 19), 1000, dtype=np.float32))
66
+
67
+
68
+ if __name__ == "__main__":
69
+ unittest.main()
tests/test_instancenorm_export.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The repaired source must never inherit old witness classifications."""
2
+ import importlib.util
3
+ from pathlib import Path
4
+ import unittest
5
+
6
+ path = Path(__file__).resolve().parents[1] / "pipeline/repair_instancenorm.py"
7
+ spec = importlib.util.spec_from_file_location("repair_instancenorm", path)
8
+ repair = importlib.util.module_from_spec(spec)
9
+ spec.loader.exec_module(repair)
10
+
11
+
12
+ def result(mid, cls):
13
+ return dict(type="RESULT", id=mid, cls=cls, rule="test-rule",
14
+ category="arithmetic", site="a * b", witness=None)
15
+
16
+
17
+ class WitnessExport(unittest.TestCase):
18
+ def test_oom_hidden_in_journal_is_not_a_mutant_kill(self):
19
+ row = result("a", "killed_by_T0")
20
+ row.update(reason="crash", detail="CUDA out of memory. Tried to allocate 7 GiB")
21
+ with self.assertRaisesRegex(RuntimeError, "Infrastructure"):
22
+ repair.check_infrastructure_failure("", [row], 3)
23
+
24
+ def test_operating_system_kill_is_not_a_mutant_kill(self):
25
+ with self.assertRaisesRegex(RuntimeError, "Infrastructure"):
26
+ repair.check_infrastructure_failure("", [], -9)
27
+
28
+ def test_matrix_only_kill_updates_witness_and_denominator(self):
29
+ screening = [result("a", "killed_by_T0"), result("b", "no_witness"),
30
+ result("c", "compile_fail"), result("d", "no_witness")]
31
+ matrix = [dict(type="CELL", id="b", suite="shifted", outcome="killed")]
32
+ witnesses, summary = repair.export_records(screening, matrix)
33
+ self.assertEqual(witnesses["b"]["cls"], "high_value")
34
+ self.assertEqual(witnesses["b"]["witness"], "shifted")
35
+ self.assertNotIn("c", witnesses)
36
+ self.assertEqual(summary, dict(mutants=3, witnessed=2,
37
+ killed_by_official=1, level=12))
38
+
39
+ def test_missing_screening_result_is_rejected(self):
40
+ with self.assertRaisesRegex(RuntimeError, "Screening"):
41
+ repair.validate_records([result("a", "no_witness")], [], {"a", "b"}, set())
42
+
43
+ def test_missing_matrix_cell_is_rejected(self):
44
+ with self.assertRaisesRegex(RuntimeError, "matrix"):
45
+ repair.validate_records([result("a", "no_witness")], [], {"a"}, {"shifted"})
46
+
47
+ def test_crash_records_do_not_require_unsafe_reexecution(self):
48
+ row = result("a", "killed_by_T0")
49
+ row["reason"] = "probe_crash"
50
+ repair.validate_records([row], [], {"a"}, {"shifted"})
51
+
52
+ def test_complete_matrix_is_accepted(self):
53
+ cell = dict(type="CELL", id="a", suite="shifted", outcome="survived")
54
+ repair.validate_records([result("a", "no_witness")], [cell], {"a"}, {"shifted"})
55
+
56
+
57
+ if __name__ == "__main__":
58
+ unittest.main()