File size: 13,897 Bytes
5d12def
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""One-case GPU evaluator. The supervisor gives each case a fresh process."""

import gc
import importlib.util
from pathlib import Path
import sys
import time

import torch

from . import baselines, extended, sparse, expansion
from .metrics import paired_summary
from .tasks import PATTERNS, TASKS, make_inputs, make_integration, reference, tensor_bytes


class InvalidSubmission(Exception):
    pass


def same_tensor_bits(a, b):
    """Integer low bits, signed zero, and opaque FP8 storage must stay unchanged."""
    return (a.shape == b.shape and a.dtype == b.dtype and a.device == b.device and
            torch.equal(a.contiguous().reshape(-1).view(torch.uint8), b.contiguous().reshape(-1).view(torch.uint8)))


def load_candidate(path, task):
    sys.path.insert(0, str(Path(path).resolve().parent))
    spec = importlib.util.spec_from_file_location("kernel_submission", path)
    module = importlib.util.module_from_spec(spec)
    sys.modules[spec.name] = module
    spec.loader.exec_module(module)
    fn = getattr(module, task)
    if not callable(fn):
        raise InvalidSubmission(f"Submission must define {task}")
    return fn


def check_output(actual, expected, contract):
    if isinstance(expected, tuple):
        if not isinstance(actual, tuple) or len(actual) != len(expected):
            raise InvalidSubmission("Output tuple structure mismatch")
        contracts = contract.get("outputs", [contract] * len(expected))
        return {"outputs": [check_output(a, e, c) for a, e, c in zip(actual, expected, contracts)]}
    if not isinstance(actual, torch.Tensor):
        raise InvalidSubmission("Output is not a torch.Tensor")
    if actual.shape != expected.shape or actual.dtype != expected.dtype or actual.device != expected.device:
        raise InvalidSubmission(f"Output metadata mismatch: shape={actual.shape}, dtype={actual.dtype}, device={actual.device}")
    af, ef = actual.float(), expected.float()
    if contract.get("allow_negative_infinity", False):
        if not torch.equal(torch.isneginf(af), torch.isneginf(ef)):
            raise InvalidSubmission("Negative-infinity sentinel mismatch")
        af, ef = (x.masked_fill(torch.isneginf(x), 0.) for x in (af, ef))
    if not torch.isfinite(af).all().item():
        raise InvalidSubmission("Non-finite output")
    if contract["rtol"] == 0 and contract["atol"] == 0 and not same_tensor_bits(actual, expected):
        raise InvalidSubmission("Exact output bits mismatch")
    error = (af - ef).abs()
    reference_rms = ef.square().mean().sqrt().item()
    rmse = error.square().mean().sqrt().item()
    nrmse = rmse / max(reference_rms, 1e-12)
    absolute_bound = max(contract["atol"], contract.get("rms_atol", 0) * reference_rms)
    bound = absolute_bound + contract["rtol"] * ef.abs()
    if 'propagated_atol' in contract:
        bound=bound+contract['propagated_atol']
    max_scaled = torch.where(bound > 0, error / bound, torch.where(error == 0, 0., float("inf"))).max().item()
    if max_scaled > 1:
        raise InvalidSubmission(f"Numerical mismatch: max error/tolerance={max_scaled:.5g}")
    if reference_rms > 0 and nrmse > contract["nrmse"]:
        raise InvalidSubmission(f"Normalized RMSE {nrmse:.5g} exceeds {contract['nrmse']}")
    return {"max_abs_error": error.max().item(), "max_error_over_tolerance": max_scaled,
            "rmse": rmse, "reference_rms": reference_rms, "nrmse": nrmse, "absolute_bound": absolute_bound}


def check_call(fn, args, expected, contract):
    snapshots = [x.clone() if isinstance(x, torch.Tensor) else x for x in args]
    actual = fn(*args)
    torch.cuda.synchronize()
    for old, new in zip(snapshots, args):
        if isinstance(old, torch.Tensor) and not same_tensor_bits(old, new):
            raise InvalidSubmission("Input mutation detected")
    stats = check_task_output(actual, expected, contract, args)
    semantic = contract.get("semantic")
    if not (extended.check_invariants(semantic, args, actual) and sparse.check_invariants(semantic, args, actual)
            and expansion.check_invariants(semantic, args, actual)):
        raise InvalidSubmission("Exact semantic invariant failed")
    return stats


def check_task_output(actual, expected, contract, args):
    if contract.get('semantic')=='multi_lora':
        from .expansion.oracle import lora_rounding_bound
        propagated=lora_rounding_bound(*args)
        stats=check_output(actual,expected,{**contract,'propagated_atol':propagated})
        stats['propagated_bf16_ulp_bound_max']=float(propagated.max())
        return stats
    if contract.get('semantic')!='dsa_indexer':
        return check_output(actual,expected,contract)
    if not isinstance(actual,tuple) or len(actual)!=2:
        raise InvalidSubmission('DSA output must be (scores, indices)')
    scores,ids=actual
    for got,want in zip(actual,expected):
        if not isinstance(got,torch.Tensor) or (got.shape,got.dtype,got.device)!=(want.shape,want.dtype,want.device):
            raise InvalidSubmission('DSA output metadata mismatch')
    if bool(((ids<0)|(ids>=args[1].shape[1])).any()):
        raise InvalidSubmission('DSA index out of range')
    ordered=ids.sort(-1).values
    if bool((ordered[...,1:]==ordered[...,:-1]).any()):
        raise InvalidSubmission('DSA duplicate index')
    if bool((scores[...,1:]>scores[...,:-1]).any()) or bool(((scores[...,1:]==scores[...,:-1])&(ids[...,1:]<ids[...,:-1])).any()):
        raise InvalidSubmission('DSA score order or exact tie order mismatch')
    from .expansion.oracle import dsa_scores
    true_scores=dsa_scores(*args[:-1])
    selected=true_scores.gather(-1,ids)
    score_contract=contract['outputs'][0]
    score_stats=check_output(scores,selected,score_contract)
    rank_stats=check_output(selected,expected[0],score_contract)
    zero=true_scores.eq(0).all(-1)
    if not torch.equal(ids[zero],expected[1][zero]):
        raise InvalidSubmission('DSA all-zero tie must select ascending IDs')
    return {'score_error':score_stats,'rank_error':rank_stats,'unique_in_range_indices':True}


def memory_usage(fn):
    gc.collect()
    torch.cuda.synchronize()
    before = torch.cuda.memory_allocated()
    torch.cuda.reset_peak_memory_stats()
    out = fn()
    torch.cuda.synchronize()
    result = {"extra_peak_allocated_bytes": max(0, torch.cuda.max_memory_allocated() - before),
              "output_bytes": sum(x.numel() * x.element_size() for x in (out if isinstance(out, tuple) else (out,)))}
    del out
    return result


def capture(fn, repeats):
    stream = torch.cuda.Stream()
    stream.wait_stream(torch.cuda.current_stream())
    with torch.cuda.stream(stream):
        for _ in range(5):
            fn()
    stream.synchronize()
    graph = torch.cuda.CUDAGraph()
    with torch.cuda.graph(graph, stream=stream):
        for _ in range(repeats):
            out = fn()
    torch.cuda.synchronize()
    # Keep the last output alive for the lifetime of the graph.
    return graph, out


def measure_pair(base_fn, candidate_fn, rounds, repeats, seed, verify_graphs=None):
    memory = {"baseline": memory_usage(base_fn), "candidate": memory_usage(candidate_fn)}
    graphs = [capture(base_fn, repeats), capture(candidate_fn, repeats)]
    for _ in range(3):
        for graph, _out in graphs:
            graph.replay()
    torch.cuda.synchronize()
    samples = [[], []]
    for round_id in range(rounds):
        # Balanced AB/BA rounds avoid giving one implementation every cold/first slot.
        order = (0, 1) if (round_id + seed) % 2 == 0 else (1, 0)
        pair = [0.0, 0.0]
        for idx in order:
            start, end = (torch.cuda.Event(enable_timing=True) for _ in range(2))
            start.record()
            graphs[idx][0].replay()
            end.record()
            end.synchronize()
            pair[idx] = start.elapsed_time(end) * 1000 / repeats
        for idx in (0, 1):
            samples[idx].append(pair[idx])
    result = paired_summary(*samples, seed=seed)
    result.update({"memory": memory, "graph_calls_per_sample": repeats,
                   "timing_mode": "cuda_graph_unrolled/warm_reused_inputs/CUDA_events"})
    if verify_graphs is not None:
        result["graph_replay_validation"] = verify_graphs(graphs)
    return result


def check_graph_replay(graph, output, args, expected, contract):
    snapshots = [x.clone() if isinstance(x, torch.Tensor) else x for x in args]
    graph.replay()
    torch.cuda.synchronize()
    for old, current in zip(snapshots, args):
        if isinstance(old, torch.Tensor) and not same_tensor_bits(old, current):
            raise InvalidSubmission("CUDA Graph input mutation detected")
    stats = check_task_output(output, expected, contract, args)
    semantic = contract.get("semantic")
    if not (extended.check_invariants(semantic, args, output) and sparse.check_invariants(semantic, args, output)
            and expansion.check_invariants(semantic, args, output)):
        raise InvalidSubmission("CUDA Graph exact semantic invariant failed")
    return stats


@torch.inference_mode()
def evaluate(case, candidate_path, seed, rounds, repeats):
    torch.cuda.set_device(0)
    torch.backends.cuda.matmul.allow_tf32 = False
    torch.backends.cudnn.allow_tf32 = False
    torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction = False
    task = case["task"]
    contract = TASKS[task]
    base_fn, baseline_name = baselines.resolve(case)
    major, minor = torch.cuda.get_device_capability()
    result = {"id": case["id"], "task": task, "case": case, "seed": seed,
              "baseline": baseline_name, "contract": contract}
    if major * 10 + minor < contract["min_sm"]:
        return {**result, "status": "unsupported", "reason": "GPU capability below contract minimum"}
    candidate_fn = load_candidate(candidate_path, task)
    checks = []
    start = time.perf_counter()
    # Baseline validation is separate: a broken baseline is an infrastructure error.
    for i, pattern in enumerate(PATTERNS):
        args = make_inputs(case, seed + i, pattern)
        expected = reference(task, *args)
        try:
            base_stats = check_call(base_fn, args, expected, contract)
        except InvalidSubmission as exc:
            raise RuntimeError(f"Baseline failed {pattern} (seed={seed + i}): {exc}") from exc
        try:
            cand_stats = check_call(candidate_fn, args, expected, contract)
        except InvalidSubmission as exc:
            raise InvalidSubmission(f"Candidate eager {pattern}: {exc}") from exc
        checks.append({"pattern": pattern, "seed": seed + i,
                       "baseline": base_stats, "candidate": cand_stats})
        del args, expected
    result["validation"] = checks
    result["compile_and_validation_seconds"] = time.perf_counter() - start
    args = make_inputs(case, seed + 100)
    expected = reference(task, *args)
    glue = make_integration(case, args, seed + 101)
    expected_block = glue(expected)
    calls = {"baseline": 0, "candidate": 0}

    def block(which, fn):
        calls[which] += 1
        return glue(fn(*args))

    block_contract = contract.get("integration_contract", {k: v for k, v in contract.items() if k != "outputs"})
    try:
        check_output(block("baseline", base_fn), expected_block, block_contract)
    except InvalidSubmission as exc:
        raise RuntimeError(f"Baseline failed integration (seed={seed + 100}): {exc}") from exc
    check_output(block("candidate", candidate_fn), expected_block, block_contract)
    result["input_bytes"] = tensor_bytes(args)

    def verify_graphs(graphs, phase):
        checks = []
        for offset in (2000, 2001):
            fresh = make_inputs(case, seed + offset)
            # CUDA Graph pointers stay fixed; only their contents change.
            for destination, source in zip(args, fresh):
                if isinstance(destination, torch.Tensor):
                    destination.copy_(source)
                elif destination != source:
                    raise RuntimeError("Graph validation requires unchanged CPU planning metadata")
            expected = reference(task, *args)
            gate = contract
            if phase == "block":
                expected = glue(expected)
                gate = {k: v for k, v in block_contract.items() if k != "semantic"}
            for which, (graph, output) in zip(("baseline", "candidate"), graphs):
                try:
                    stats = check_graph_replay(graph, output, args, expected, gate)
                except InvalidSubmission as exc:
                    if which == "baseline":
                        raise RuntimeError(f"Baseline failed {phase} graph replay (seed={seed + offset}): {exc}") from exc
                    raise InvalidSubmission(f"Candidate {phase} graph replay failed: {exc}") from exc
                checks.append({"implementation": which, "seed": seed + offset, **stats})
        original = make_inputs(case, seed + 100)
        for destination, source in zip(args, original):
            if isinstance(destination, torch.Tensor):
                destination.copy_(source)
        return checks

    result["kernel"] = measure_pair(lambda: base_fn(*args), lambda: candidate_fn(*args), rounds, repeats, seed,
                                    lambda graphs: verify_graphs(graphs, "kernel"))
    result["block"] = measure_pair(lambda: block("baseline", base_fn),
                                   lambda: block("candidate", candidate_fn), rounds, repeats, seed + 1,
                                   lambda graphs: verify_graphs(graphs, "block"))
    result["integration_calls"] = calls
    # Fresh data after timing catches common output-caching/stateful mistakes.
    fresh = make_inputs(case, seed + 1000)
    result["post_timing_check"] = check_call(candidate_fn, fresh, reference(task, *fresh), contract)
    return {**result, "status": "passed"}