File size: 16,173 Bytes
addfd4b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
"""Validate and time actual solutions against independent task references."""

import argparse
import contextlib
import fcntl
import hashlib
import importlib.util
import json
import os
from pathlib import Path
import statistics
import sys
import time
import traceback

from task_acceptance import compare_output

parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1])
parser.add_argument(
    "--data-root", type=Path, help="Optional materialized dataset with the same paths"
)
parser.add_argument("--lock-directory", type=Path, required=True)
parser.add_argument(
    "--cache-directory", type=Path, help="Writable module and reference cache"
)
parser.add_argument("--definition", action="append")
parser.add_argument("--suite", choices=["first", "dev", "all"], default="first")
parser.add_argument("--only-default", action="store_true")
parser.add_argument("--report", required=True, type=Path)
parser.add_argument("--validation-only", action="store_true")
parser.add_argument("--scale-probe", action="store_true")
parser.add_argument("--gpu", required=True)
parser.add_argument("--workload", action="append")
parser.add_argument("--solution", action="append")
parser.add_argument(
    "--candidate",
    action="append",
    default=[],
    help="Extra run() module for comparing a candidate on one selected definition",
)
parser.add_argument("--reference-cache", action="store_true")
parser.add_argument("--graph-timing", action="store_true")
parser.add_argument(
    "--strict-diagnostic",
    action="store_true",
    help="Also report the historical FP32 bound for GDN; does not affect task acceptance",
)
args = parser.parse_args()
SOURCE = args.root.resolve()
DATA = args.data_root.resolve() if args.data_root else SOURCE
CACHE = (
    args.cache_directory.resolve()
    if args.cache_directory
    else SOURCE / "results/audit-cache"
)
GPU = args.gpu
LOCKS = args.lock_directory
LOCKS.mkdir(exist_ok=True, parents=True)
os.environ["CUDA_VISIBLE_DEVICES"] = GPU
stack = contextlib.ExitStack()
for suffix in ["", ".lock"]:
    handle = stack.enter_context((LOCKS / (GPU + suffix)).open("a+"))
    fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)

import torch
from safetensors.torch import load_file

torch.set_num_threads(8)
torch.backends.cuda.matmul.allow_tf32 = False
torch._inductor.config.compile_threads = 1


def load_function(name, path):
    identifier = "_audit_" + hashlib.sha256(name.encode()).hexdigest()[:20]
    package = path.parent
    spec = importlib.util.spec_from_file_location(
        identifier, package / "__init__.py", submodule_search_locations=[str(package)]
    )
    if path.name != "main.py":
        spec = importlib.util.spec_from_file_location(identifier, path)
    module = importlib.util.module_from_spec(spec)
    sys.modules[identifier] = module
    spec.loader.exec_module(module)
    if path.name == "main.py":
        spec = importlib.util.spec_from_file_location(identifier + ".main", path)
        child = importlib.util.module_from_spec(spec)
        sys.modules[spec.name] = child
        spec.loader.exec_module(child)
        module = child
    return module.run, getattr(module, "prepare", None)


def normalize(result, definition):
    return (
        list(result.values())
        if isinstance(result, dict)
        else list(result)
        if isinstance(result, (tuple, list))
        else [result]
    )


def compare(actual, expected, definition, config):
    values = normalize(actual, definition)
    assert len(values) == len(expected)
    metrics = {}
    for name, value, reference in zip(definition["outputs"], values, expected):
        metrics[name] = compare_output(value, reference, config["tolerance"])
    return metrics


def measure(function, inputs, timing):
    for _ in range(timing["warmup"]):
        _result = function(*inputs)
    torch.cuda.synchronize()
    samples = []
    for _ in range(timing["iters"] * timing["trials"]):
        start = torch.cuda.Event(enable_timing=True)
        end = torch.cuda.Event(enable_timing=True)
        start.record()
        _result = function(*inputs)
        end.record()
        end.synchronize()
        samples.append(start.elapsed_time(end) * 1000)
    return {
        "median_us": statistics.median(samples),
        "samples_us": samples,
        "method": "CUDA events over eager calls",
    }


def measure_graph(function, inputs, timing, definition, config, expected):
    for _ in range(max(3, timing["warmup"])):
        result = function(*inputs)
    torch.cuda.synchronize()
    graph = torch.cuda.CUDAGraph()
    with torch.cuda.graph(graph):
        for _ in range(timing["iters"]):
            result = function(*inputs)
    graph.replay()
    torch.cuda.synchronize()
    compare(result, expected, definition, config)
    samples = []
    for _ in range(timing["trials"]):
        start = torch.cuda.Event(enable_timing=True)
        end = torch.cuda.Event(enable_timing=True)
        start.record()
        graph.replay()
        end.record()
        end.synchronize()
        samples.append(start.elapsed_time(end) * 1000 / timing["iters"])
    return {
        "median_us": statistics.median(samples),
        "samples_us": samples,
        "method": "CUDA graph, iters calls per replay",
        "calls_per_replay": timing["iters"],
    }


definitions = {
    json.loads(f.read_text())["name"]: json.loads(f.read_text())
    for f in (SOURCE / "definitions").rglob("*.json")
}
solutions = {}
for f in (SOURCE / "solutions").rglob("*.json"):
    s = json.loads(f.read_text())
    solutions.setdefault(s["definition"], []).append(s)
rows_by_name = {
    f.stem: [json.loads(l)["workload"] for l in f.read_text().splitlines()]
    for f in (SOURCE / "workloads").rglob("*.jsonl")
}
args.report.parent.mkdir(exist_ok=True, parents=True)
failures = 0
with args.report.open("w") as report, torch.inference_mode():

    def emit(row):
        report.write(json.dumps(row) + "\n")
        report.flush()

    emit(
        {
            "type": "environment",
            "gpu": torch.cuda.get_device_name(),
            "torch": torch.__version__,
            "suite": args.suite,
            "pythonpath": os.environ.get("PYTHONPATH"),
            "started_at": time.time(),
        }
    )
    for name, definition in definitions.items():
        if args.definition and name not in args.definition:
            continue
        config = json.loads((SOURCE / "tasks" / f"{name}.json").read_text())
        rows = rows_by_name[name]
        if args.suite == "dev":
            rows = [row for row in rows if row["uuid"] in config["dev"]]
        if args.suite == "first":
            rows = rows[:1]
        if args.workload:
            rows = [row for row in rows if row["uuid"] in args.workload]
        candidates = []
        for solution in solutions[name]:
            if args.only_default and solution["name"] == "sglang_" + name:
                continue
            digest = hashlib.sha256(
                json.dumps(solution, sort_keys=True).encode()
            ).hexdigest()
            package = CACHE / "modules" / digest
            for source in solution["sources"]:
                target = package / source["path"]
                if not target.resolve().is_relative_to(package.resolve()):
                    raise ValueError("Source path escapes package")
                target.parent.mkdir(parents=True, exist_ok=True)
                target.write_text(source["content"])
            (package / "__init__.py").touch()
            entry = solution["spec"]["entry_point"].split("::")[0]
            candidates.append((solution["name"], package / entry))
        if args.candidate:
            assert args.definition and len(args.definition) == 1
            candidates.extend((Path(p).stem, Path(p)) for p in args.candidate)
        if args.solution:
            candidates = [(s, p) for s, p in candidates if s in args.solution]
        ns = {}
        exec(definition["reference"], ns)
        reference = ns["run"]
        for solution, path in candidates:
            try:
                function, prepare = load_function(solution, path)
            except Exception:
                failures += 1
                emit(
                    {
                        "type": "load",
                        "definition": name,
                        "solution": solution,
                        "status": "failed",
                        "error": traceback.format_exc(),
                    }
                )
                print("LOAD FAILED", name, solution, flush=True)
                continue
            for row in rows:
                inputs = []
                saved = []
                expected = []
                result = {
                    "type": "workload",
                    "definition": name,
                    "solution": solution,
                    "uuid": row["uuid"],
                    "axes": row["axes"],
                    "solution_sha256": hashlib.sha256(path.read_bytes()).hexdigest(),
                    "definition_sha256": hashlib.sha256(
                        json.dumps(definition, sort_keys=True).encode()
                    ).hexdigest(),
                    "task_sha256": hashlib.sha256(
                        json.dumps(config, sort_keys=True).encode()
                    ).hexdigest(),
                }
                try:
                    for key in definition["inputs"]:
                        desc = row["inputs"][key]
                        value = (
                            desc["value"]
                            if desc["type"] == "scalar"
                            else load_file(str(DATA / desc["path"]), device="cuda")[
                                desc["tensor_key"]
                            ]
                        )
                        inputs.append(value)
                        saved.append(
                            value.clone() if isinstance(value, torch.Tensor) else value
                        )
                    cache_key = hashlib.sha256(
                        json.dumps(
                            {
                                "reference": definition["reference"],
                                "row": row,
                                "torch": torch.__version__,
                            },
                            sort_keys=True,
                        ).encode()
                    ).hexdigest()
                    cache = CACHE / "references" / (cache_key + ".pt")
                    if args.reference_cache and cache.exists():
                        expected = [
                            value.to("cuda")
                            for value in torch.load(cache, weights_only=True)
                        ]
                    else:
                        expected = [
                            value.clone()
                            for value in normalize(reference(*inputs), definition)
                        ]
                        if args.reference_cache:
                            cache.parent.mkdir(exist_ok=True, parents=True)
                            torch.save([value.cpu() for value in expected], cache)
                    actual_result = function(*inputs)
                    result["errors"] = compare(
                        actual_result, expected, definition, config
                    )
                    if args.strict_diagnostic and name.startswith("gdn_"):
                        result["strict_fp32_diagnostic"] = {}
                        for key, value, target in zip(
                            definition["outputs"],
                            normalize(actual_result, definition),
                            expected,
                        ):
                            if value.dtype == torch.float32:
                                close = torch.isclose(
                                    value, target, rtol=1e-4, atol=2e-5
                                )
                                result["strict_fp32_diagnostic"][key] = {
                                    "rtol": 1e-4,
                                    "atol": 2e-5,
                                    "mismatched_elements": int((~close).sum()),
                                    "elements": close.numel(),
                                    "passes": bool(close.all()),
                                }
                    for key, value, original in zip(
                        definition["inputs"], inputs, saved
                    ):
                        if isinstance(value, torch.Tensor):
                            assert torch.equal(
                                value.contiguous().view(torch.uint8),
                                original.contiguous().view(torch.uint8),
                            ), key + " input mutated"
                    if args.scale_probe and "scale" in definition["inputs"]:
                        index = list(definition["inputs"]).index("scale")
                        original = inputs[index]
                        inputs[index] = (
                            definition["axes"]["head_size"]["value"] ** -0.5
                            if original is None or original == 0
                            else original
                        ) * 0.5
                        target = [
                            value.clone()
                            for value in normalize(reference(*inputs), definition)
                        ]
                        result["scale_probe"] = compare(
                            function(*inputs), target, definition, config
                        )
                        inputs[index] = original
                    if not args.validation_only:
                        result["run_timing"] = measure(
                            function, inputs, config["timing"]
                        )
                        if prepare:
                            launch = prepare(*inputs)
                            result["prepared_timing"] = measure(
                                lambda *unused: launch(), inputs, config["timing"]
                            )
                        if args.graph_timing:
                            try:
                                launch_function = (
                                    (lambda *unused: launch()) if prepare else function
                                )
                                result["graph_timing"] = measure_graph(
                                    launch_function,
                                    inputs,
                                    config["timing"],
                                    definition,
                                    config,
                                    expected,
                                )
                            except Exception:
                                result["graph_error"] = traceback.format_exc()
                    for key, value, original in zip(
                        definition["inputs"], inputs, saved
                    ):
                        if isinstance(value, torch.Tensor):
                            assert torch.equal(
                                value.contiguous().view(torch.uint8),
                                original.contiguous().view(torch.uint8),
                            ), key + " input mutated during timing"
                    result["inputs_unchanged"] = True
                    result["status"] = "passed"
                except Exception:
                    failures += 1
                    result.update(status="failed", error=traceback.format_exc())
                emit(result)
                print(
                    result["status"],
                    name,
                    solution,
                    row["axes"],
                    result.get("run_timing", {}).get("median_us"),
                    flush=True,
                )
                inputs = saved = expected = actual_result = None
            function = prepare = None

if failures:
    raise SystemExit(f"{failures} failed cases; see {args.report}")