File size: 6,478 Bytes
1276a5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
"""Evaluate all variants (correct + mutants) of one problem against all test suites.

Kill criterion follows KernelBench eval: runtime error, shape mismatch, or
!torch.allclose(ref, out, atol=1e-2, rtol=1e-2)  => killed.

Writes JSONL journal (one line per variant x suite). Resumable: already-journaled
(variant, suite) pairs are skipped; a START line without a matching RESULT line
(previous process died there) is recorded as killed:process_crash, and all
remaining suites of that variant are skipped.

Usage: python3 eval_kernel.py <problem> <journal_path>
"""
import importlib.util
import json
import os
import sys

import torch

import kernels_def as K

ATOL = RTOL = 1e-2


def load_ref_model(problem):
    p = K.PROBLEMS[problem]
    spec = importlib.util.spec_from_file_location(f"kb_{problem}", p["kb_file"])
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    init = mod.get_init_inputs()
    return mod.Model(*init), init


def build_ext(problem, variant_id, cuda_src):
    from torch.utils.cpp_extension import load_inline
    p = K.PROBLEMS[problem]
    return load_inline(
        name=f"{problem}_{variant_id}",
        cpp_sources=p["cpp"],
        cuda_sources=cuda_src,
        functions=[p["func"]],
        verbose=False,
    )


def compare(ref, out):
    if not isinstance(out, torch.Tensor):
        return dict(status="killed", reason="not_a_tensor")
    if out.shape != ref.shape:
        return dict(status="killed", reason="shape_mismatch",
                    detail=f"{tuple(out.shape)} vs {tuple(ref.shape)}")
    ok = torch.allclose(ref, out, atol=ATOL, rtol=RTOL)
    if ok:
        return dict(status="survived")
    diff = (ref - out).abs()
    finite = torch.isfinite(out).all().item()
    return dict(status="killed", reason="value_mismatch",
                max_diff=float(diff.nan_to_num(nan=float("inf")).max()),
                out_finite=bool(finite))


def main():
    problem, journal_path = sys.argv[1], sys.argv[2]
    p = K.PROBLEMS[problem]

    done = {}        # (variant, suite) -> True
    crashed = set()  # variants that crashed a previous process
    pending_start = None
    if os.path.exists(journal_path):
        for line in open(journal_path):
            rec = json.loads(line)
            if rec["type"] == "START":
                pending_start = (rec["variant"], rec["suite"])
            elif rec["type"] == "RESULT":
                done[(rec["variant"], rec["suite"])] = True
                pending_start = None

    journal = open(journal_path, "a")

    def emit(rec):
        journal.write(json.dumps(rec) + "\n")
        journal.flush()
        os.fsync(journal.fileno())

    # a START without RESULT means the previous process died on that (variant, suite)
    if pending_start is not None:
        v, s = pending_start
        emit(dict(type="RESULT", variant=v, suite=s, trial=-1,
                  status="killed", reason="process_crash"))
        done[(v, s)] = True
        crashed.add(v)

    ref_model, _ = load_ref_model(problem)
    ref_model = ref_model.cuda().eval()
    suites = p["suites"]()

    # cache reference outputs on CPU: (suite, trial) -> ref_out
    ref_cache = {}

    def ref_out_for(suite_name, builder, trial):
        key = (suite_name, trial)
        if key not in ref_cache:
            inputs = builder(trial)
            with torch.no_grad():
                gpu_in = [t.cuda() for t in inputs]
                ref_cache[key] = ref_model(*gpu_in).cpu()
                del gpu_in
                torch.cuda.empty_cache()
        return ref_cache[key]

    for variant_id, cuda_src in K.all_variants(problem):
        if variant_id in crashed:
            for suite_name, _, _ in suites:
                if (variant_id, suite_name) not in done:
                    emit(dict(type="RESULT", variant=variant_id, suite=suite_name, trial=-1,
                              status="skipped_after_crash"))
            continue

        try:
            ext = build_ext(problem, variant_id, cuda_src)
        except Exception as e:
            for suite_name, _, _ in suites:
                if (variant_id, suite_name) not in done:
                    emit(dict(type="RESULT", variant=variant_id, suite=suite_name, trial=-1,
                              status="killed", reason="compile_error", detail=str(e)[:300]))
            continue

        wrapper_cls = p["wrapper"]
        if problem == "sum":
            model_new = wrapper_cls(ext, 1)
        else:
            model_new = wrapper_cls(ext)
        model_new = model_new.cuda().eval()

        variant_dead = False
        for suite_name, n_trials, builder in suites:
            if (variant_id, suite_name) in done:
                continue
            if variant_dead:
                emit(dict(type="RESULT", variant=variant_id, suite=suite_name, trial=-1,
                          status="skipped_after_crash"))
                continue
            emit(dict(type="START", variant=variant_id, suite=suite_name))
            result = dict(status="survived")
            for trial in range(n_trials):
                ref_out = ref_out_for(suite_name, builder, trial)
                inputs = builder(trial)
                try:
                    with torch.no_grad():
                        gpu_in = [t.cuda() for t in inputs]
                        out = model_new(*gpu_in)
                        torch.cuda.synchronize()
                        r = compare(ref_out.cuda(), out)
                        del gpu_in, out
                        torch.cuda.empty_cache()
                except RuntimeError as e:
                    r = dict(status="killed", reason="runtime_error", detail=str(e)[:300])
                    if "CUDA" in str(e) or "cuda" in str(e):
                        # context may be poisoned; record and let the driver restart us
                        r["trial"] = trial
                        emit(dict(type="RESULT", variant=variant_id, suite=suite_name, **r))
                        journal.close()
                        sys.exit(3)
                if r["status"] == "killed":
                    r["trial"] = trial
                    result = r
                    break
            if "trial" not in result:
                result["trial"] = n_trials
            emit(dict(type="RESULT", variant=variant_id, suite=suite_name, **result))

    emit(dict(type="DONE", problem=problem))
    journal.close()


if __name__ == "__main__":
    main()