"""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], []), "", "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. / m.) 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())