Repository navigation
Expand file tree
/
Copy patheval.py
More file actions
308 lines (253 loc) · 9.57 KB
/
Copy patheval.py
File metadata and controls
308 lines (253 loc) · 9.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
import dataclasses
import math
import multiprocessing
import os
import re
import sys
import time
from pathlib import Path
from typing import Any, Optional
import torch
from reference import check_implementation, generate_input
from utils import clear_l2_cache, set_seed
try:
from task import TestSpec
except ImportError:
TestSpec = dict
MAX_ITERATIONS_PER_BENCHMARK = 50
BENCHMARK_INPUT_BYTES_TARGET = 256 * 1024 * 1024
class PopcornOutput:
def __init__(self, fd: int):
self.file = os.fdopen(fd, "w")
os.set_inheritable(fd, False)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.file.close()
def print(self, *args, **kwargs):
print(*args, **kwargs, file=self.file, flush=True)
def log(self, key, value):
self.print(f"{key}: {value}")
@dataclasses.dataclass
class TestCase:
args: dict
spec: str
@dataclasses.dataclass
class Stats:
runs: int
mean: float
std: float
err: float
best: float
worst: float
def _combine(a: int, b: int) -> int:
return int(a + (a + b) * (a + b + 1) // 2)
def get_test_cases(file_name: str, seed: Optional[int]) -> list[TestCase]:
try:
content = Path(file_name).read_text()
except Exception as exc:
print(f"Could not open test file `{file_name}`: {exc}", file=sys.stderr)
exit(113)
tests = []
match = r"\s*([a-zA-Z_][a-zA-Z0-9_]*):\s*([a-zA-Z_][a-zA-Z0-9_]*|[+-]?[0-9]+)\s*"
for line in content.splitlines():
case = {}
for part in line.split(";"):
matched = re.match(match, part)
if not re.fullmatch(match, part):
print(f"invalid test case: '{line}': '{part}'", file=sys.stderr)
exit(113)
key = matched[1]
val = matched[2]
try:
val = int(val)
except ValueError:
pass
case[key] = val
tests.append(TestCase(spec=line, args=case))
if seed is not None:
for test in tests:
if "seed" in test.args:
test.args["seed"] = _combine(test.args["seed"], seed)
return tests
def calculate_stats(durations: list[float]) -> Stats:
runs = len(durations)
total = sum(durations)
avg = total / runs
variance = sum((x - avg) ** 2 for x in durations)
std = math.sqrt(variance / (runs - 1)) if runs > 1 else 0.0
err = std / math.sqrt(runs) if runs > 0 else 0.0
return Stats(
runs=runs,
mean=avg,
std=std,
err=err,
best=float(min(durations)),
worst=float(max(durations)),
)
def _clone_data(data):
if isinstance(data, tuple):
return tuple(_clone_data(x) for x in data)
if isinstance(data, list):
return [_clone_data(x) for x in data]
if isinstance(data, dict):
return {k: _clone_data(v) for k, v in data.items()}
if isinstance(data, torch.Tensor):
return data.clone()
return data
def _run_single_test(test: TestCase):
from submission import custom_kernel
data = generate_input(**test.args)
torch.cuda.synchronize()
output = custom_kernel(_clone_data(data))
torch.cuda.synchronize()
return check_implementation(data, output)
def run_single_test(pool: multiprocessing.Pool, test: TestCase):
return pool.apply(_run_single_test, (test,))
def run_testing(logger: PopcornOutput, pool: multiprocessing.Pool, tests: list[TestCase]):
passed = True
logger.log("test-count", len(tests))
for idx, test in enumerate(tests):
logger.log(f"test.{idx}.spec", test.spec)
good, message = run_single_test(pool, test)
if good:
logger.log(f"test.{idx}.status", "pass")
if message:
logger.log(f"test.{idx}.message", message)
else:
logger.log(f"test.{idx}.status", "fail")
logger.log(f"test.{idx}.error", message)
passed = False
logger.log("check", "pass" if passed else "fail")
return 0 if passed else 112
def _make_data_batch(test: TestCase, count: int):
args = dict(test.args)
data_list = []
for _ in range(count):
if "seed" in args:
args["seed"] += 42
data_list.append(generate_input(**args))
return data_list
def _benchmark_batch_count(test: TestCase) -> int:
batch = int(test.args.get("batch", 1))
n = int(test.args.get("n", 1))
bytes_per_input = (batch * n * n) * 4
if bytes_per_input <= 0:
return 1
return max(1, min(MAX_ITERATIONS_PER_BENCHMARK, BENCHMARK_INPUT_BYTES_TARGET // bytes_per_input))
def _run_single_benchmark(
test: TestCase,
recheck: bool,
max_repeats: int,
max_time_ns: float,
) -> Stats | Any:
from submission import custom_kernel
data_list = _make_data_batch(test, _benchmark_batch_count(test))
check_copy = _clone_data(data_list)
outputs = [custom_kernel(_clone_data(data)) for data in data_list]
for reference_data, output in zip(check_copy, outputs):
good, message = check_implementation(reference_data, output)
if not good:
return message
durations = []
bm_start_time = time.perf_counter_ns()
for i in range(max_repeats):
if recheck:
# Regenerate a FRESH input batch every timed iteration so no
# submission can memoize / cache / graph-replay an output keyed on a
# reused input. Bump the spec seed (the secret-seed-combined value)
# so each iteration draws a distinct, never-before-seen batch, then
# rebuild data_list and its reference copy. Generation happens before
# the timing window below, so it is not charged to the kernel.
if "seed" in test.args:
test.args["seed"] += 13
data_list = _make_data_batch(test, _benchmark_batch_count(test))
check_copy = _clone_data(data_list)
torch.cuda.synchronize()
clear_l2_cache()
start_event = torch.cuda.Event(enable_timing=True)
end_event = torch.cuda.Event(enable_timing=True)
start_event.record()
outputs = [custom_kernel(data) for data in data_list]
end_event.record()
torch.cuda.synchronize()
durations.append(start_event.elapsed_time(end_event) * 1e6 / len(data_list))
if recheck:
for reference_data, output in zip(check_copy, outputs):
good, message = check_implementation(reference_data, output)
if not good:
return message
total_bm_duration = time.perf_counter_ns() - bm_start_time
if i > 1 and total_bm_duration > 1e8:
stats = calculate_stats(durations)
if (
stats.err / stats.mean < 0.001
or stats.mean * stats.runs > max_time_ns
or total_bm_duration > 120e9
):
break
return calculate_stats(durations)
def run_single_benchmark(
pool: multiprocessing.Pool,
test: TestCase,
recheck: bool,
max_repeats: int,
max_time_ns: float,
):
return pool.apply(_run_single_benchmark, (test, recheck, max_repeats, max_time_ns))
def run_benchmarking(logger: PopcornOutput, pool: multiprocessing.Pool, tests: list[TestCase]):
run_single_benchmark(pool, tests[0], False, 200, 10e7)
passed = True
logger.log("benchmark-count", len(tests))
for idx, test in enumerate(tests):
logger.log(f"benchmark.{idx}.spec", test.spec)
result = run_single_benchmark(pool, test, True, 200, 10e9)
if isinstance(result, Stats):
for field in dataclasses.fields(Stats):
logger.log(f"benchmark.{idx}.{field.name}", getattr(result, field.name))
else:
logger.log(f"benchmark.{idx}.status", "fail")
logger.log(f"benchmark.{idx}.error", result)
passed = False
logger.log("check", "pass" if passed else "fail")
return 0 if passed else 112
def main():
fd = os.getenv("POPCORN_FD")
if not fd:
return 111
if len(sys.argv) < 3:
return 2
mode = sys.argv[1]
seed = os.getenv("POPCORN_SEED")
os.unsetenv("POPCORN_SEED")
seed = int(seed) if seed else None
set_seed(seed or 42)
tests = get_test_cases(sys.argv[2], seed)
with PopcornOutput(int(fd)) as logger:
mp_context = multiprocessing.get_context("spawn")
with mp_context.Pool(1) as pool:
if mode == "test":
return run_testing(logger, pool, tests)
if mode == "benchmark":
return run_benchmarking(logger, pool, tests)
if mode == "leaderboard":
for test in tests:
run_single_benchmark(pool, test, False, 1000, 5e8)
logger.log("benchmark-count", len(tests))
passed = True
for idx, test in enumerate(tests):
logger.log(f"benchmark.{idx}.spec", test.spec)
result = run_single_benchmark(pool, test, True, 1000, 30e9)
if isinstance(result, Stats):
for field in dataclasses.fields(Stats):
logger.log(f"benchmark.{idx}.{field.name}", getattr(result, field.name))
else:
logger.log(f"benchmark.{idx}.status", "fail")
logger.log(f"benchmark.{idx}.error", str(result))
passed = False
break
logger.log("check", "pass" if passed else "fail")
return 0 if passed else 112
return 2
if __name__ == "__main__":
sys.exit(main())