File size: 14,483 Bytes
902d2bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: CC-BY-NC-4.0
"""Robustness: correct on new valid shapes and on special input values, not only on the shipped ones."""
from __future__ import annotations

import ast
import json
import operator
import os
import random
import re

from .. import harness

# Passing the shipped workloads is not enough: a kernel can be keyed to them. The shape part
# learns each axis's values from the shipped workloads, with the axes that are always equal and
# the pairs that are always ordered (a <= b). It then makes new valid shapes: values no shipped
# workload used (inside an axis's range), one axis above its max (up to 2x), boundary mixes and
# new mixes of shipped values, under a size cap. Axes named in the definition's constraints keep
# a shipped combination. The value part runs special values on the smallest shape. A failure of
# the reference itself is no evidence against the kernel: such cases are re-run (or run first)
# with the definition's reference code and left out. Only ROBUST passes; INCONCLUSIVE does not.
# The check only reads your local copy of the benchmark.
GATING = ("small", "alt_sign", "constant")     # special values that decide the verdict
REPORT_ONLY = ("large",)                       # x100 values: recorded, not in the verdict
FLOAT_DTYPES = frozenset({"float32", "float16", "bfloat16", "float64"})
_REF_SUSPECT = frozenset({"INVALID_REFERENCE", "INCORRECT_SHAPE", "INCORRECT_DTYPE"})
_OPS = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul,
        ast.Div: operator.truediv, ast.FloorDiv: operator.floordiv, ast.Mod: operator.mod,
        ast.Pow: operator.pow}


def _int(v):
    return isinstance(v, int) and not isinstance(v, bool)


def _size(axes):
    n = 1
    for v in axes.values():
        n *= max(1, v) if _int(v) else 1
    return n


def analyze(workloads):
    """(values per axis, groups of axes that are always equal, pairs (a, b) with a <= b always)."""
    axes = sorted({a for w in workloads for a, v in w["axes"].items() if _int(v)})
    values = {a: sorted({w["axes"][a] for w in workloads if a in w["axes"]}) for a in axes}
    root = {a: a for a in axes}

    def find(a):
        while root[a] != a:
            a = root[a]
        return a
    le = set()
    for i, a in enumerate(axes):
        for b in axes[i + 1:]:
            pairs = [(w["axes"][a], w["axes"][b]) for w in workloads
                     if a in w["axes"] and b in w["axes"]]
            if pairs and all(x == y for x, y in pairs):
                root[find(b)] = find(a)
            elif pairs and all(x <= y for x, y in pairs):
                le.add((a, b))
            elif pairs and all(x >= y for x, y in pairs):
                le.add((b, a))
    groups = {}
    for a in axes:
        groups.setdefault(find(a), []).append(a)
    return values, list(groups.values()), le


def _unused(vals, rng):
    lo, hi = vals[0], vals[-1]
    if hi <= lo:
        return None
    cands = {v + d for v in vals for d in (-1, 1)} | {rng.randrange(lo, hi + 1) | 1 for _ in range(4)}
    cands = sorted(c for c in cands if lo <= c <= hi and c > 0 and c not in vals)
    return rng.choice(cands) if cands else None


def plan_shapes(defn, workloads, n=12, seed=0):
    """Up to n new valid shapes: [{"axes", "kind", "base"}] (base = the shipped workload used)."""
    rng = random.Random(seed)
    values, groups, le = analyze(workloads)
    named = set()
    for c in defn.get("constraints") or []:
        named.update(re.findall(r"[A-Za-z_]\w*", str(c)))
    free = [g for g in groups if not set(g) & named]
    gvals = [sorted({v for a in g for v in values[a]}) for g in free]
    cap = max(_size(w["axes"]) for w in workloads)
    seen, out = {tuple(sorted(w["axes"].items())) for w in workloads}, []

    def add(base, picks, kind, scale=1):
        axes = dict(workloads[base]["axes"])
        for gi, v in picks.items():
            axes.update((a, v) for a in free[gi])
        key = tuple(sorted(axes.items()))
        if (key in seen or _size(axes) > scale * cap
                or any(axes.get(a, 0) > axes.get(b, 0) for a, b in le)):
            return
        seen.add(key)
        out.append({"axes": axes, "kind": kind, "base": base})

    for t in range(50 * n if free else 0):     # unused values, and one axis above its max
        if len(out) >= (n + 1) // 2:
            break
        gi, base = rng.randrange(len(free)), rng.randrange(len(workloads))
        above = t % 2 == 0 and sum(s["kind"] == "above_max" for s in out) < max(1, n // 6)
        hi = gvals[gi][-1]
        if above:
            v = rng.randrange(hi + 1, 2 * hi + 1) if hi > 0 else None
        else:
            v = _unused(gvals[gi], rng)
        if v is not None:
            add(base, {gi: v}, "above_max" if above else "unused_value", 2 if above else 1)
    for pick in (min, max) if free else ():    # boundary mixes
        add(0, {gi: pick(vals) for gi, vals in enumerate(gvals)}, "boundary")
    for _ in range(50 * n if free else 0):     # new mixes of shipped values
        if len(out) >= n:
            break
        add(rng.randrange(len(workloads)), {gi: rng.choice(v) for gi, v in enumerate(gvals)},
            "new_mix")
    return out[:n]


def reference_solution(defn):
    """The definition's own reference code as a PyTorch solution (read from your local copy)."""
    # The harness refuses Python sources that contain the word "stream"; NVIDIA's own
    # scripts/run_dataset.py renames it the same way before it runs a reference.
    code = str(defn.get("reference") or "").replace("stream", "strm")
    return {"name": "reference", "definition": defn.get("name"), "author": "reference",
            "spec": {"languages": ["pytorch"], "target_hardware": ["LOCAL"],
                     "entry_point": "reference.py::run", "dependencies": ["torch"],
                     "destination_passing_style": False},
            "sources": [{"path": "reference.py", "content": code}]}


def _run(problem_dir, sol_path, lines, out_dir, name, kw):
    """{uuid: trace row} for one harness run of these workload lines (correctness only)."""
    if not lines:
        return {}
    wl = harness.write_jsonl(os.path.join(out_dir, name + ".jsonl"), lines)
    res = harness.evaluate(problem_dir, sol_path, os.path.join(out_dir, name), workload_path=wl,
                           config_path=harness.quick_config(out_dir), **kw)
    return {r.get("uuid"): r for r in res["rows"]}


def _line(base, axes, uuid):
    """A workload line: a shipped workload with new axes (a scalar input named like an axis follows it)."""
    ins = {k: dict(d, value=axes[k]) if isinstance(d, dict) and d.get("type") == "scalar"
           and k in axes and _int(d.get("value")) else d for k, d in (base.get("inputs") or {}).items()}
    return dict(base, axes=axes, uuid=uuid, inputs=ins)


def _suspect(row):
    return row["status"] in _REF_SUSPECT or (row["status"] == "INCORRECT_NUMERICAL"
                                             and row.get("nonfinite"))


def shape_part(problem_dir, sol_path, ref_path, defn, workloads, n, seed, out_dir, kw):
    usable = [w for w in workloads if isinstance(w.get("axes"), dict)
              and not any((d or {}).get("type") == "safetensors" for d in (w.get("inputs") or {}).values())]
    plan = plan_shapes(defn, usable, n, seed) if usable else []
    if not plan:
        return {"tested": 0, "failed": [], "skipped": "fixed_tensors" if not usable else "no_new_shape"}
    lines = [_line(usable[s["base"]], s["axes"], "robust-shape-%d" % i) for i, s in enumerate(plan)]
    rows = _run(problem_dir, sol_path, lines, out_dir, "shapes", kw)
    suspects = [ln for ln in lines if ln["uuid"] in rows and _suspect(rows[ln["uuid"]])]
    ref = _run(problem_dir, ref_path, suspects, out_dir, "shapes_reference", kw)
    failed, excluded, missing = [], [], 0
    for ln, s in zip(lines, plan):
        r = rows.get(ln["uuid"])
        if r is None:
            missing += 1
        elif r["status"] == "PASSED":
            continue
        elif _suspect(r) and (ref.get(ln["uuid"]) or {}).get("status") != "PASSED":
            excluded.append(s["axes"])                 # the reference fails there too
        else:
            failed.append({"axes": s["axes"], "kind": s["kind"], "status": r["status"]})
    return {"tested": len(plan) - missing - len(excluded), "failed": failed, "missing": missing,
            "excluded_reference_fails": excluded,
            "above_max_only": bool(failed) and all(f["kind"] == "above_max" for f in failed)}


def _eval_axis(text, vals):
    def ev(n):
        if isinstance(n, ast.Expression):
            return ev(n.body)
        if isinstance(n, ast.Constant) and isinstance(n.value, (int, float)):
            return n.value
        if isinstance(n, ast.Name):
            return vals[n.id]
        if isinstance(n, ast.BinOp) and type(n.op) in _OPS:
            return _OPS[type(n.op)](ev(n.left), ev(n.right))
        if isinstance(n, ast.UnaryOp) and isinstance(n.op, (ast.USub, ast.UAdd)):
            return -ev(n.operand) if isinstance(n.op, ast.USub) else ev(n.operand)
        raise ValueError("unsupported axis expression")
    return ev(ast.parse(str(text), mode="eval"))


def input_shapes(defn, axes):
    """Concrete shapes of the tensor inputs for one workload's axes (const, var and expr axes)."""
    vals, specs = dict(axes), defn.get("axes") or {}
    vals.update((k, s.get("value")) for k, s in specs.items() if s.get("type") == "const")
    for _ in specs:                                   # expr axes may build on each other
        for k, s in specs.items():
            if s.get("type") == "expr" and k not in vals:
                try:
                    vals[k] = _eval_axis(s.get("expression"), vals)
                except (KeyError, ValueError, ZeroDivisionError):
                    pass
    return {k: [int(vals[d]) if isinstance(d, str) else int(d) for d in v["shape"]]
            for k, v in (defn.get("inputs") or {}).items() if v.get("shape") is not None}


def _values(torch, name, shape, dtype, gen):
    """One input tensor of special values (made in fp32, then cast to the declared dtype)."""
    if name == "small":
        x = torch.randn(shape, generator=gen) * 1e-3
    elif name == "alt_sign":
        sign = 1 - 2 * (torch.arange(torch.Size(shape).numel()) % 2)
        x = (1.0 + torch.rand(shape, generator=gen)) * sign.reshape(shape)
    elif name == "constant":
        x = torch.full(shape, 0.5)
    else:
        x = torch.randn(shape, generator=gen) * 100.0
    return x.to(dtype).contiguous()


def value_part(problem_dir, sol_path, ref_path, defn, seed, out_dir, kw):
    try:
        import torch
        from safetensors.torch import save_file
    except ImportError:
        return {"tested": 0, "failed": [], "skipped": "needs_torch_and_safetensors"}
    base = harness.smallest_workload(problem_dir) or {}
    tensors = {k: v for k, v in (defn.get("inputs") or {}).items() if v.get("shape") is not None}
    if not tensors or any(str(v.get("dtype")) not in FLOAT_DTYPES for v in tensors.values()):
        return {"tested": 0, "failed": [], "skipped": "non_float_inputs"}
    if any((d or {}).get("type") in ("custom", "safetensors") for d in (base.get("inputs") or {}).values()):
        return {"tested": 0, "failed": [], "skipped": "custom_inputs"}
    try:
        shapes, gen, lines = input_shapes(defn, base.get("axes") or {}), torch.Generator(), {}
        gen.manual_seed(seed)
        for pat in GATING + REPORT_ONLY:
            data = {k: _values(torch, pat, shapes[k], getattr(torch, str(v["dtype"])), gen)
                    for k, v in tensors.items()}
            path = os.path.abspath(os.path.join(out_dir, "values_%s.safetensors" % pat))
            save_file(data, path)
            ins = dict(base.get("inputs") or {})
            ins.update((k, {"type": "safetensors", "path": path, "tensor_key": k}) for k in tensors)
            lines[pat] = dict(base, uuid="robust-values-" + pat, inputs=ins)
    except (KeyError, ValueError, TypeError, RuntimeError) as e:
        return {"tested": 0, "failed": [], "skipped": "input_error", "error": type(e).__name__}
    ref = _run(problem_dir, ref_path, list(lines.values()), out_dir, "values_reference", kw)
    ok = [p for p in lines if (ref.get(lines[p]["uuid"]) or {}).get("status") == "PASSED"]
    rows = _run(problem_dir, sol_path, [lines[p] for p in ok], out_dir, "values", kw)
    failed, report, missing = [], {}, 0
    for p in ok:
        r = rows.get(lines[p]["uuid"])
        if p in REPORT_ONLY:
            report[p] = r["status"] if r else None
        elif r is None:
            missing += 1
        elif r["status"] != "PASSED":
            failed.append({"values": p, "status": r["status"]})
    return {"tested": sum(p in GATING for p in ok) - missing, "failed": failed, "missing": missing,
            "excluded_reference_fails": [p for p in GATING if p not in ok], "report_only": report}


def check(problem_dir, solution_path, out_dir, gpu_id=None, lock_dir=None, n_shapes=12, seed=0,
          values=True, compile_timeout_s=300, eval_timeout_s=1800) -> dict:
    """{"verdict": ROBUST | NOT_ROBUST | INCONCLUSIVE, "shapes": {...}, "values": {...}}."""
    with open(os.path.join(problem_dir, "definition.json"), encoding="utf-8") as f:
        defn = json.load(f)
    shipped = [w for w in harness.read_jsonl(os.path.join(problem_dir, "workload.jsonl"))
               if isinstance(w, dict)]
    os.makedirs(out_dir, exist_ok=True)
    ref_path = os.path.join(out_dir, "reference_solution.json")
    with open(ref_path, "w", encoding="utf-8") as f:
        json.dump(reference_solution(defn), f)
    kw = {"gpu_id": gpu_id, "lock_dir": lock_dir, "compile_timeout_s": compile_timeout_s,
          "eval_timeout_s": eval_timeout_s}
    shapes = shape_part(problem_dir, solution_path, ref_path, defn, shipped, n_shapes, seed,
                        out_dir, kw)
    vals = (value_part(problem_dir, solution_path, ref_path, defn, seed, out_dir, kw) if values
            else {"tested": 0, "failed": [], "skipped": "off"})
    if shapes["failed"] or vals["failed"]:
        verdict = "NOT_ROBUST"
    elif shapes.get("missing") or vals.get("missing") or not (shapes["tested"] + vals["tested"]):
        verdict = "INCONCLUSIVE"
    else:
        verdict = "ROBUST"
    return {"verdict": verdict, "shapes": shapes, "values": vals}