File size: 10,562 Bytes
2e4c7fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51dbbd3
 
 
 
 
 
 
 
 
2e4c7fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51dbbd3
2e4c7fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51dbbd3
 
 
 
 
 
 
 
 
 
2e4c7fe
 
 
51dbbd3
 
 
 
 
 
 
 
 
2e4c7fe
 
51dbbd3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e4c7fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51dbbd3
 
 
 
 
2e4c7fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Emit a schema-conformant record per task, and validate it against task.schema.json.

This is the machine-readable contract for the suite. It is DERIVED from what is on disk -- the grader's
TOL/shape lists, the reference source, the catalog's family and difficulty -- so it cannot drift from
the tasks themselves.

The split that matters: DEFINITION (maths + graded interface + correctness policy) is separate from
WORKLOAD (the shapes). Today every task has one workload, "synthetic", sized so the kernel dominates.
A captured workload -- shapes recorded from a real serving or sampling run -- drops in beside it
without touching the definition or duplicating the task.

    python3 _factory/audit_schema.py [task ...]      -> writes TASKS.json, reports violations
"""
import ast
import json
import pathlib
import re
import sys

LANE = pathlib.Path(__file__).resolve().parent.parent
SCHEMA = pathlib.Path(__file__).resolve().parent / "schema" / "task.schema.json"
ONLY = set(sys.argv[1:])

COMPARATOR = {"tuple": "relative-frobenius-tuple-max", "rowwise": "rowwise",
              "tensor": "relative-frobenius"}


def const(src, name, default=None):
    """Module-level constant by AST. A single-line regex misses the many multi-line shape lists."""
    try:
        tree = ast.parse(src)
    except SyntaxError:
        return default
    for n in tree.body:
        if isinstance(n, ast.Assign):
            # tuple unpacking: BATCH, PREFILL, MAX_SEQ = 1, 2048, 4096
            for t in n.targets:
                if isinstance(t, ast.Tuple) and isinstance(n.value, ast.Tuple):
                    for tgt, val in zip(t.elts, n.value.elts):
                        if isinstance(tgt, ast.Name) and tgt.id == name:
                            try:
                                return ast.literal_eval(val)
                            except Exception:
                                pass
            for t in n.targets:
                if isinstance(t, ast.Name) and t.id == name:
                    try:
                        return ast.literal_eval(n.value)
                    except Exception:
                        pass
                    try:                       # non-literal (comprehension, arithmetic): evaluate it
                        ns = {}
                        exec(compile(ast.Module([n], []), "<c>", "exec"), ns)
                        return ns.get(name, default)
                    except Exception:
                        return default
    return default


def emit(task):
    d = LANE / task
    v = d / "tests" / "verify_env.py"
    if not v.exists():
        return None
    src = v.read_text()
    metric = "GB/s" if "GB/s" in src else "TFLOP/s"
    tol = const(src, "TOL")
    if tol is None:
        tol = const(src, "PERF_TOL")
    comp = "relative-frobenius"
    if const(src, "NAMES") is not None:
        comp = "relative-frobenius-tuple-max"
    if const(src, "ROW_PASS") is not None:
        comp = "rowwise"
    if tol == 0:
        comp = "exact"

    # three harness layouts: factory (fn = m.x), legacy (return m.x inside _load), megakernel
    # (m.<entry_build> / m.<entry_step>)
    entry = (re.search(r"fn = m\.(\w+)", src) or re.search(r"return m\.(\w+)", src)
             or re.search(r"hs = m\.(\w+)", src) or re.search(r"got = m\.(\w+)", src)
             or re.search(r'getattr\(m, "(\w+)"', src))
    if entry is None:                          # dist-* graders resolve the entry via their spec
        for sub in ("_dist_factory", "_factory", "_mega_factory"):
            sp = LANE / sub / "specs" / (task.replace("-", "_") + ".py")
            if sp.exists():
                fm = re.search(r'func\s*=\s*"(\w+)"', sp.read_text())
                if fm:
                    entry = fm
                    break
    dims = []
    graded = const(src, "GRADER_SHAPES", []) or []
    correct = const(src, "CORRECT_SHAPES", []) or []
    measure = const(src, "MEASURE_SHAPES", []) or []
    # the megakernel family has no shape tuples: its workload is an architecture config plus a
    # decode regime, so express that as a single graded point rather than pretending it has none.
    if not graded:
        cfg = const(src, "CFG")
        if isinstance(cfg, dict):
            dims_mk = ["layers", "d", "n_q", "n_kv", "hd", "vocab"]
            pt = [cfg.get(k, 0) for k in dims_mk] + [const(src, "BATCH", 1),
                                                     const(src, "PREFILL", 0),
                                                     const(src, "DECODE_STEPS", 0)]
            dims = dims_mk + ["batch", "prefill", "decode_steps"]
            graded = correct = [pt]

    def _params(fn_src):
        """Positional dim names of a function: drop defaulted params (chunk_size=64) and `seed`."""
        out = []
        for raw in fn_src.split(","):
            nm = raw.split("=")[0].strip()
            if not nm or "=" in raw or nm in ("seed", "self") or nm.startswith("*"):
                continue
            out.append(nm)
        return out

    cw = ""
    m = re.search(r"^def canonical_work\(([^)]*)\)", src, re.M)
    if m:
        dims = _params(m.group(1))
    if not dims:
        # legacy graders name the work function differently; the input generator's signature is the
        # authoritative list of dims either way
        mk = re.search(r"^def _(?:mk|make)\(([^)]*)\)", src, re.M)
        if mk:
            dims = _params(mk.group(1))
    if m:
        r = re.search(r"return (.+)", src[m.start():])
        cw = r.group(1).strip() if r else ""

    # Most authoritative of all: how the grader itself unpacks a shape tuple. A legacy shape can carry
    # config the input generator does not name as a parameter (flash-attn-backward's causal flag).
    if graded:
        want = len(graded[0])
        if len(dims) != want:
            for pat in (r"for\s+\w+,\s*\(([^)]+)\)\s+in\s+enumerate\(\s*(?:GRADER|CORRECT)_SHAPES",
                        r"for\s+\(([^)]+)\)\s+in\s+(?:GRADER|CORRECT)_SHAPES",
                        r"\(([^)]+)\)\s*=\s*shp\b"):
                u = re.search(pat, src)
                if u:
                    cand = [x.strip() for x in u.group(1).split(",") if x.strip()]
                    if len(cand) == want:
                        dims = cand
                        break

    rec = {
        "name": task,
        "family": CAT.get(task, {}).get("family", "Other"),
        "description": CAT.get(task, {}).get("description", ""),
        "keywords": CAT.get(task, {}).get("keywords", []),
        "definition": {
            "entry_point": entry.group(1) if entry else "",
            "module": (re.search(r"MODULE_PATH = \"/app/([^\"]+)\"", src) or [None, ""])[1]
                      if "MODULE_PATH" in src else "",
            "inputs": [], "outputs": [],
            "reference": {"language": "python/pytorch",
                          "source": f"{task}/environment/reference.py"},
        },
        "workloads": {
            "synthetic": {
                "source": "synthetic",
                "dims": dims,
                "graded": [list(s) for s in graded],
                "correctness": [list(s) for s in correct],
                "measure": [list(s) for s in measure],
                **({"roofline_us": CAT[task]["roofline_us"]}
                   if CAT.get(task, {}).get("roofline_us") is not None else {}),
            }
        },
        "grading": {
            "metric": metric,
            "reward": {"kind": "absolute-uncapped", "canonical_work": cw},
            "tolerance": {"value": tol if tol is not None else 0.0, "comparator": comp},
        },
        "environment": {
            "gpus": CAT.get(task, {}).get("gpus", 1),
            "min_compute_capability": "9.0",
            "offline": True,
            "note": "The exact GPU is deliberately not specified; the task tells the agent to query it.",
        },
    }
    t = DIFF.get(task)
    if t:
        rec["difficulty"] = {"tier": t[0], "rationale": t[1],
                             "reviewed_by_hand": task in HANDREVIEWED}
    rp = const(src, "ROW_PASS")
    if rp is not None:
        rec["grading"]["tolerance"]["row_pass"] = rp
    return rec


CAT = {}
p = LANE / "CATALOG.json"
if p.exists():
    CAT = {r["name"]: r for r in json.loads(p.read_text())}
DIFF, HANDREVIEWED = {}, set()
p = LANE / "_factory" / "difficulty.json"
if p.exists():
    for r in json.loads(p.read_text()):
        DIFF[r["name"]] = (r["tier"], r["why"])
try:
    sys.path.insert(0, str(LANE / "_factory"))
    from difficulty import OVERRIDE
    HANDREVIEWED = set(OVERRIDE)
except Exception:
    pass


def main():
    tasks = sorted(x.name for x in LANE.iterdir()
                   if x.is_dir() and not x.name.startswith("_") and (x / "task.toml").exists())
    if ONLY:
        tasks = [t for t in tasks if t in ONLY]
    recs, bad = [], []
    for t in tasks:
        r = emit(t)
        if r is None:
            bad.append((t, "no grader")); continue
        for req in ("name", "family", "definition", "workloads", "grading"):
            if req not in r:
                bad.append((t, f"missing {req}"))
        if not r["definition"]["entry_point"]:
            bad.append((t, "no entry point discoverable"))
        w = r["workloads"]["synthetic"]
        if not w["graded"] or not w["correctness"]:
            bad.append((t, "workload has no graded/correctness shapes"))
        elif w["dims"] and any(len(sh) != len(w["dims"]) for sh in w["graded"]):
            n = next(len(sh) for sh in w["graded"] if len(sh) != len(w["dims"]))
            bad.append((t, f"{len(w['dims'])} dim names for a {n}-value shape"))
        elif not w["dims"]:
            bad.append((t, "workload shapes have no dim names"))
        recs.append(r)
    (LANE / "TASKS.json").write_text(json.dumps(recs, indent=2) + "\n")

    try:
        import jsonschema
        sch = json.loads(SCHEMA.read_text())
        for r in recs:
            try:
                jsonschema.validate(r, sch)
            except jsonschema.ValidationError as e:
                bad.append((r["name"], f"schema: {e.message[:90]}"))
        note = "validated against task.schema.json"
    except ImportError:
        note = "jsonschema not installed; structural checks only"

    print(f"emitted {len(recs)} task records -> TASKS.json ({note})")
    if bad:
        print(f"  {len(bad)} issues:")
        for t, m in bad[:15]:
            print(f"    {t}: {m}")
    else:
        print("  no issues")
    return 1 if bad else 0


if __name__ == "__main__":
    sys.exit(main())