File size: 9,817 Bytes
65e1c10
 
 
 
 
 
 
 
 
 
 
 
addfd4b
 
65e1c10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
addfd4b
 
65e1c10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
addfd4b
 
 
 
65e1c10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Build native Trace solutions, validate complete outputs, and time on a local GPU."""

import argparse
import contextlib
import fcntl
import json
import os
from pathlib import Path
import statistics
import time
import traceback

from task_acceptance import compare_output


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1])
    parser.add_argument("--capture-root", type=Path, help="Read fresh capture inputs and receipts from this directory")
    parser.add_argument("--solution", action="append", help="Solution name substring; repeatable")
    parser.add_argument("--gpu", required=True, help="Local NVIDIA GPU UUID")
    parser.add_argument("--lock-directory", type=Path, required=True)
    parser.add_argument("--report", type=Path, required=True)
    parser.add_argument("--limit", type=int, help="Maximum workloads per solution for an initial check")
    parser.add_argument("--validation-only", action="store_true")
    parser.add_argument("--compare-to", choices=("reference", "capture"), default="reference")
    parser.add_argument("--workload", action="append", help="Restrict to these workload UUIDs")
    args = parser.parse_args()
    root = args.root.resolve()
    data_root = args.capture_root.resolve() if args.capture_root else root
    cache = root / "results/baselines/cache"
    for name, suffix in {
        "FIB_CACHE_PATH": "trace", "XDG_CACHE_HOME": "xdg",
        "TRITON_CACHE_DIR": "triton", "TORCHINDUCTOR_CACHE_DIR": "inductor",
        "TORCH_EXTENSIONS_DIR": "extensions", "CUDA_CACHE_PATH": "cuda",
        "FLASHINFER_WORKSPACE_BASE": "flashinfer", "TVM_FFI_CACHE_DIR": "tvm",
        "DG_JIT_CACHE_DIR": "deepgemm", "SGLANG_CACHE_DIR": "sglang",
        "TILELANG_CACHE_DIR": "tilelang",
    }.items():
        os.environ.setdefault(name, str(cache / suffix))
    os.environ["CUDA_VISIBLE_DEVICES"] = args.gpu
    os.environ.setdefault("OMP_NUM_THREADS", "8")
    os.environ.setdefault("MAX_JOBS", "32")
    args.lock_directory.mkdir(parents=True, exist_ok=True)
    args.report.parent.mkdir(parents=True, exist_ok=True)
    with contextlib.ExitStack() as stack:
        for suffix in ("", ".lock"):
            lock = stack.enter_context((args.lock_directory / (args.gpu + suffix)).open("a+"))
            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        import torch
        from safetensors.torch import load_file
        from flashinfer_bench.compile import BuilderRegistry
        from flashinfer_bench.data import Definition, Solution

        torch.set_num_threads(8)
        torch.backends.cuda.matmul.allow_tf32 = False
        definitions = {
            definition.name: definition
            for path in (root / "definitions").rglob("*.json")
            for definition in [Definition.model_validate_json(path.read_text())]
        }
        receipt_path = data_root / "captures.jsonl"
        if not receipt_path.exists():
            receipt_path = data_root / "results/captures.jsonl"
        receipts = {
            row["uuid"]: row for line in receipt_path.read_text().splitlines()
            for row in [json.loads(line)]
        }
        workloads = {}
        for path in (data_root / "workloads").rglob("*.jsonl"):
            for line in path.read_text().splitlines():
                row = json.loads(line)
                workloads.setdefault(row["definition"], []).append(row["workload"])
        solutions = [
            solution for path in sorted((root / "solutions").rglob("*.json"))
            for solution in [Solution.model_validate_json(path.read_text())]
            if not args.solution or any(name in solution.name for name in args.solution)
        ]
        if not solutions:
            raise ValueError("No solutions selected")

        def load(descriptor):
            if descriptor["type"] == "scalar":
                return descriptor["value"]
            if descriptor["type"] != "safetensors":
                raise ValueError("Only complete captured inputs are accepted")
            return load_file(str(data_root / descriptor["path"]), device="cuda")[descriptor["tensor_key"]]

        def compare(actual, expected, definition, output_name):
            config = json.loads((root / 'tasks' / f'{definition}.json').read_text())
            return compare_output(actual, expected, config['tolerance'])

        def measure(function):
            for _ in range(3):
                function()
            torch.cuda.synchronize()
            graph = torch.cuda.CUDAGraph()
            with torch.cuda.graph(graph):
                graph_output = function()
            graph.replay()
            torch.cuda.synchronize()
            start, end = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
            start.record()
            graph.replay()
            end.record()
            end.synchronize()
            single_ms = start.elapsed_time(end)
            repeats = max(1, min(1000, int(20 / max(single_ms, .001))))
            samples = []
            for _ in range(5):
                start.record()
                for _ in range(repeats):
                    graph.replay()
                end.record()
                end.synchronize()
                samples.append(start.elapsed_time(end) * 1000 / repeats)
            return {"median_us": statistics.median(samples), "samples_us": samples,
                    "repeats": repeats, "method": "CUDA events over CUDA Graph replays",
                    "scope": "complete solution call, including input adapters"}

        failures = 0
        with args.report.open("w") as report, torch.inference_mode():
            header = {"type": "environment", "gpu_uuid": args.gpu,
                      "gpu_name": torch.cuda.get_device_name(), "torch": torch.__version__,
                      "started_at": time.time(), "comparison": "all output elements against " + args.compare_to,
                      "solution_count": len(solutions)}
            report.write(json.dumps(header) + "\n")
            report.flush()
            for solution in solutions:
                definition = definitions[solution.definition]
                if definition.name not in workloads:
                    raise ValueError(f"No captured workloads for {definition.name}")
                runnable = BuilderRegistry.get_instance().build(definition, solution)
                selected = workloads[definition.name]
                if args.workload:
                    selected = [workload for workload in selected if workload["uuid"] in args.workload]
                if args.limit is not None:
                    selected = selected[:args.limit]
                reference = None
                if args.compare_to == "reference":
                    namespace = {}
                    exec(compile(definition.reference, definition.name, "exec"), namespace)
                    reference = namespace["run"]
                for workload in selected:
                    row = {"type": "workload", "solution": solution.name,
                           "definition": definition.name, "uuid": workload["uuid"],
                           "axes": workload["axes"]}
                    inputs = actual = expected = outputs = reference_outputs = None
                    try:
                        inputs = [load(workload["inputs"][key]) for key in definition.inputs]
                        actual = runnable(*inputs)
                        outputs = list(actual) if isinstance(actual, (tuple, list)) else [actual]
                        descriptors = receipts[workload["uuid"]].get("expected_output")
                        if reference is None and descriptors is None:
                            raise ValueError("This imported workload has no saved engine output; compare to reference")
                        if descriptors is not None and "type" in descriptors:
                            descriptors = {next(iter(definition.outputs)): descriptors}
                        if len(outputs) != len(definition.outputs):
                            raise AssertionError("Output count differs")
                        if reference is not None:
                            reference_result = reference(*inputs)
                            reference_outputs = list(reference_result) if isinstance(reference_result, (tuple, list)) else [reference_result]
                            reference_result = None
                        row["errors"] = {}
                        for index, (key, value) in enumerate(zip(definition.outputs, outputs)):
                            expected = reference_outputs[index] if reference_outputs is not None else load(descriptors[key])
                            row["errors"][key] = compare(value, expected, definition.name, key)
                        row["validation"] = "passed"
                        actual = expected = outputs = reference_outputs = None
                        if not args.validation_only:
                            row["timing"] = measure(lambda: runnable(*inputs))
                        row["status"] = "passed"
                    except Exception:
                        row.update(status="failed", error=traceback.format_exc())
                        failures += 1
                    finally:
                        inputs = actual = expected = outputs = reference_outputs = None
                    report.write(json.dumps(row) + "\n")
                    report.flush()
                    print(row["status"], solution.name, workload["axes"],
                          row.get("timing", {}).get("median_us"), flush=True)
        if failures:
            raise SystemExit(f"{failures} failed workloads; see {args.report}")


if __name__ == "__main__":
    main()