KBench / tools /factory /audit_quality.py
ZMC2019's picture
400 tasks: kernel-optimization agent, profiler permissions, relaxed exact gates (part 22)
9f1b277 verified
Raw
History Blame Contribute Delete
8.93 kB
"""Static production-readiness audit for every kernel task.
Checks the three things that actually break a task in the field, all of which this session has now
seen happen for real:
PRECISION a tolerance that was inherited rather than measured. The default is 2e-2; a task sitting
on the default with no measured figure quoted in its prose has an unjustified gate.
Both failure directions are real: megakernel-mamba-hybrid shipped tol only 1.06x above an
honest fp32 twin (would reject CORRECT kernels), and a too-loose gate passes wrong ones.
CONTRACT every argument in the graded signature must appear in the contract table with a shape and
a dtype, and the return contract must state its dtype.
PROMPT the stated shape regime must match the shapes actually graded, and the instruction must
tell the agent to push for speed. Worst case seen: grpo-logprob-ratio's perf_md gave a
gradient with the opposite SIGN to its own spec block -- an agent reading the performance
section would score 0.
Usage: python3 _factory/audit_quality.py [task ...] (no args = whole lane)
"""
import ast
import json
import pathlib
import re
import sys
LANE = pathlib.Path(__file__).resolve().parent.parent
DEFAULT_TOL = 2e-2
ONLY = set(sys.argv[1:])
NUM = re.compile(r"\b\d+(?:\.\d+)?(?:[eE][-+]?\d+)?\b")
def spec_path(task):
p = LANE / "_factory" / "specs" / (task.replace("-", "_") + ".py")
return p if p.exists() else None
def grader_facts(task):
"""(tol, grader_shapes, correct_shapes, func) straight out of the generated grader."""
v = LANE / task / "tests" / "verify_env.py"
if not v.exists():
return None
src = v.read_text()
out = {"src": src}
for key in ("TOL", "GRADER_SHAPES", "CORRECT_SHAPES", "MEASURE_SHAPES"):
m = re.search(rf"^{key}\s*=\s*(.+?)(?:\s*#.*)?$", src, re.M)
if m:
try:
out[key] = ast.literal_eval(m.group(1).strip())
except Exception:
pass
# hand-written graders name the same gate PERF_TOL / REL_TOL / ROW_TOL; treat them as TOL rather
# than reporting a tolerance that plainly exists as missing
if "TOL" not in out:
for alias in ("PERF_TOL", "REL_TOL", "ROW_TOL"):
m = re.search(rf"^{alias}\s*=\s*(.+?)(?:\s*#.*)?$", src, re.M)
if m:
try:
out["TOL"] = ast.literal_eval(m.group(1).strip())
break
except Exception:
pass
m = re.search(r"fn = m\.(\w+)", src)
out["func"] = m.group(1) if m else None
return out
def audit(task):
issues = []
d = LANE / task
instr = (d / "instruction.md")
if not instr.exists():
return ["no instruction.md"]
text = instr.read_text()
g = grader_facts(task)
if g is None:
return ["no tests/verify_env.py"]
# ---- PRECISION -------------------------------------------------------------------------------
tol = g.get("TOL")
if tol is None:
issues.append("PRECISION: grader has no TOL")
else:
# is a measured basis quoted anywhere in the instruction?
prec = ""
m = re.search(r"^## Precision.*?$(.*?)(?=^## |\Z)", text, re.S | re.M)
if m:
prec = m.group(1)
corr = ""
for hdr in (r"^## How success is decided", r"^## Grading", r"^## Correctness"):
m = re.search(hdr + r".*?$(.*?)(?=^## |\Z)", text, re.S | re.M)
if m:
corr += m.group(1)
blob = prec + corr
# A measured basis looks like a small number that is NOT just the tolerance restated. But an
# explicitly LABELLED measurement counts at any magnitude: a bit-exact floor is E = 0.0, and a
# drop-the-feature variant is routinely D = 1.4 -- both fall outside the "small number"
# heuristic and were being reported as missing when they were right there.
flat = blob.replace(",", "")
nums = [float(x) for x in NUM.findall(flat) if _is_err_like(x)]
cited = [x for x in nums if abs(x - tol) > tol * 0.05]
labelled = re.findall(r"\b[ED]\s*=\s*\*{0,2}`?(-?\d+\.?\d*(?:[eE][-+]?\d+)?)", flat)
cited += [float(x) for x in labelled]
if tol == 0:
# an exact gate. There is no numerical error to measure -- the task is pure data movement
# (permute, gather, scatter, reshape) and any bit difference is a real bug. What it DOES
# need is for the instruction to say the comparison is exact, so nobody aims at a
# tolerance that is not there.
if not re.search(r"bit[- ]?exact|bit[- ]?identical|bit[- ]for[- ]bit|byte[- ]for[- ]byte|"
r"exactly zero|exactly equal|exact equality|must match exactly|"
r"tolerance of 0|zero tolerance", text, re.I):
issues.append("PRECISION: tol=0 (exact gate) but the instruction never says the "
"comparison is bit-exact")
elif abs(tol - DEFAULT_TOL) < 1e-12 and not cited:
issues.append(f"PRECISION: tol={tol} is the DEFAULT and no measured error is quoted "
f"-> tolerance likely never measured")
elif not cited:
issues.append(f"PRECISION: tol={tol} but no measured error quoted as its basis")
# ---- CONTRACT ---------------------------------------------------------------------------------
sig = re.search(r"^def (\w+)\((.*?)\)", text, re.M)
if sig:
args = [a.split("=")[0].strip() for a in sig.group(2).split(",") if a.strip()]
con = ""
m = re.search(r"^## The contract.*?$(.*?)(?=^## |\Z)", text, re.S | re.M)
if m:
con = m.group(1)
missing = [a for a in args if not re.search(rf"`{re.escape(a)}`", con)]
if missing:
issues.append(f"CONTRACT: args not described in the contract table: {', '.join(missing)}")
if con and not re.search(r"bfloat16|float16|float32|bf16|fp16|fp32|fp8|int8|int32|int64|uint8|bool",
con):
issues.append("CONTRACT: contract table states no dtypes")
if con and not re.search(r"\*\*Return|Returns?\b", con):
issues.append("CONTRACT: no explicit return contract")
# ---- PROMPT -----------------------------------------------------------------------------------
if not re.search(r"fast|faster|speed|throughput|performance|TFLOP|GB/s|uncapped", text, re.I):
issues.append("PROMPT: never asks the agent to go fast")
reg = ""
m = re.search(r"^## The contract.*?$(.*?)(?=^## |\Z)", text, re.S | re.M)
# regime prose lives at the end of the contract section in the generated layout
reg = (m.group(1) if m else "") + text
if g.get("GRADER_SHAPES"):
shapes = list(g["GRADER_SHAPES"]) + list(g.get("MEASURE_SHAPES") or [])
if shapes and all(isinstance(s, (list, tuple)) for s in shapes):
for pos in range(len(shapes[0])):
vals = sorted({s[pos] for s in shapes if len(s) > pos})
big = max(vals)
# a stated regime that tops out below what is actually graded is a lie to the agent
if big >= 1024 and not re.search(rf"\b{big}\b", text):
stated = [int(x) for x in re.findall(r"\b(\d{3,7})\b", text)]
if stated and max(stated) < big:
issues.append(f"PROMPT: graded dim reaches {big} but prose never exceeds "
f"{max(stated)} -> stale regime text")
break
return issues
def _is_err_like(x):
try:
v = float(x)
except Exception:
return False
return 0 < v < 1.0
def main():
tasks = sorted(p.name for p in LANE.iterdir()
if p.is_dir() and not p.name.startswith("_") and (p / "instruction.md").exists())
if ONLY:
tasks = [t for t in tasks if t in ONLY]
report, counts = {}, {"PRECISION": 0, "CONTRACT": 0, "PROMPT": 0}
for t in tasks:
iss = audit(t)
if iss:
report[t] = iss
for i in iss:
for k in counts:
if i.startswith(k):
counts[k] += 1
(LANE / "_factory" / "quality_report.json").write_text(json.dumps(report, indent=2) + "\n")
print(f"audited {len(tasks)} tasks; {len(report)} have findings")
for k, v in counts.items():
print(f" {k:10s} {v}")
return report
if __name__ == "__main__":
r = main()
for t, iss in sorted(r.items()): # print every finding: a silent cap reads
# as 'that is all of them'
print(f"\n{t}")
for i in iss:
print(" ", i)