| """Input-span audit for a task's correctness gate. |
| |
| A tolerance is only trustworthy if the error it gates on is STABLE across the seeds the grader |
| actually uses. Four things can break that, all traceable to how the inputs are drawn: |
| |
| 1. SEED SPREAD of E. The grader validates the last TIMED rep on seeds 10000+i, which are different |
| from the correctness seeds 100+i. If E varies a lot with the seed, a submission can pass |
| correctness and fail the timed check. Reported as max/min over many seeds. |
| |
| 2. SCALE ROUNDING by granularity. A scale drawn from a continuous distribution is not exactly |
| representable in bf16. A PER-TENSOR (scalar) scale's rounding error multiplies the whole output |
| coherently and shows at full magnitude; per-row/per-block scales average out over the reduction. |
| Reported per float argument, with its element count. |
| |
| 3. ENERGY CONCENTRATION. Relative Frobenius error is dominated by the largest output elements. If a |
| few elements carry most of the energy the gate is effectively reading only those. Reported as the |
| share held by the top 0.1%. |
| |
| 4. BLOCK DYNAMIC RANGE. absmax/rms over 128-element blocks of each input. A gaussian block gives |
| ~3.2; much higher means outliers dominate and everything else is crushed by quantisation. |
| |
| Run inside a task container with its tests/ mounted: |
| docker run --rm --gpus device=N -v <task>/tests:/tests:ro -v span_check.py:/app/s.py:ro IMG \ |
| python3 /app/s.py |
| """ |
| import inspect |
| import sys |
|
|
| import torch |
|
|
| sys.path.insert(0, "/app") |
|
|
| |
| V = {"__file__": "/tests/verify_env.py", "__name__": "_grader"} |
| _src = open("/tests/verify_env.py").read().split("def _bench_fresh")[0] |
| exec(compile(_src.replace('sys.path.insert(0, "/app")', ""), "<grader>", "exec"), V) |
|
|
| MK = V.get("_mk") or V.get("_make") |
| TOL = V.get("TOL") if V.get("TOL") is not None else V.get("PERF_TOL") |
| SHAPES = V.get("CORRECT_SHAPES") or V.get("GRADER_SHAPES") |
|
|
| |
| |
| REF = V.get("_ref") |
| |
| import os as _os |
| _rn = _os.environ.get("SPAN_REF", "") |
| if REF is None and _rn and callable(V.get(_rn)): |
| REF = V[_rn] |
| print(f"SPAN ref_by_name={_rn}") |
| |
| if REF is None: |
| for k in ("ref_fp32", "ref_mla"): |
| if callable(V.get(k)): |
| REF = V[k]; print(f"SPAN ref_by_name={k}"); break |
| if REF is None: |
| for k, f in V.items(): |
| if k.startswith("ref_") and callable(f) and hasattr(f, "__code__"): |
| REF = f; print(f"SPAN ref_by_prefix={k}"); break |
|
|
| if REF is None and MK is not None and SHAPES: |
| try: |
| n = len(MK(*SHAPES[0], seed=101)) |
| except Exception: |
| n = None |
| if n: |
| import inspect as _i |
| cands = [] |
| for k, f in V.items(): |
| if (k.startswith("_") or not callable(f) or not hasattr(f, "__code__") |
| or "flop" in k.lower() or "work" in k.lower() or "byte" in k.lower()): |
| continue |
| try: |
| ps = list(_i.signature(f).parameters.values()) |
| except (TypeError, ValueError): |
| continue |
| req = sum(1 for p in ps if p.default is _i.Parameter.empty |
| and p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD)) |
| if req <= n <= len(ps): |
| cands.append((abs(len(ps) - n), k, f)) |
| if cands: |
| cands.sort() |
| REF = cands[0][2] |
| print(f"SPAN ref_discovered={cands[0][1]}") |
|
|
| if REF is None or MK is None or not SHAPES: |
| have = [k for k in ("_ref", "_mk", "_make", "TOL", "PERF_TOL") if V.get(k) is not None] |
| print(f"SPAN: unsupported grader layout (found: {have or 'nothing'})") |
| raise SystemExit(0) |
|
|
| NSEED = 60 |
| SEEDS = list(range(101, 101 + NSEED)) |
|
|
|
|
| def floats(x, out=None): |
| out = [] if out is None else out |
| if torch.is_tensor(x): |
| if x.is_floating_point(): |
| out.append(x) |
| elif isinstance(x, (tuple, list)): |
| for y in x: |
| floats(y, out) |
| return out |
|
|
|
|
| def rel(a, b): |
| return float((a.float() - b.float()).norm() / b.float().norm().clamp(min=1e-30)) |
|
|
|
|
| def energy_top(t, frac=0.001): |
| e = t.float().reshape(-1) ** 2 |
| k = max(1, int(e.numel() * frac)) |
| return float(e.topk(k).values.sum() / e.sum().clamp(min=1e-30)) |
|
|
|
|
| def block_range(t, blk=128): |
| f = t.float().reshape(-1) |
| n = (f.numel() // blk) * blk |
| if n == 0: |
| return None |
| b = f[:n].view(-1, blk) |
| return float((b.abs().amax(1) / b.pow(2).mean(1).sqrt().clamp(min=1e-30)).max()) |
|
|
|
|
| shp = SHAPES[0] |
| print(f"SPAN shape={shp} TOL={TOL} seeds={NSEED}") |
|
|
| |
| errs, tops, rngs = [], [], [] |
| for s in SEEDS: |
| a = MK(*shp, seed=s) |
| out = floats(REF(*a)) |
| if not out: |
| print("SPAN: no float output; gate is exact/integer -> span audit N/A") |
| break |
| o = out[0] |
| tops.append(energy_top(o)) |
| for t in floats(a): |
| r = block_range(t) |
| if r is not None: |
| rngs.append(r) |
| b = tuple(x.bfloat16().to(x.dtype) if torch.is_tensor(x) and x.is_floating_point() else x |
| for x in a) |
| bo = floats(REF(*b)) |
| if bo: |
| errs.append(rel(bo[0], o)) |
|
|
| if errs: |
| lo, hi = min(errs), max(errs) |
| ratio = hi / max(lo, 1e-30) |
| flag = "" |
| if TOL and hi > 0: |
| head = TOL / hi |
| flag = f" headroom_worst={head:.2f}x" + (" <-- THIN" if head < 2.0 else "") |
| print(f"SPAN seed_spread E {lo:.3e}..{hi:.3e} ratio={ratio:.1f}x{flag}") |
| if tops: |
| print(f"SPAN energy_top0.1% {min(tops):.4f}..{max(tops):.4f}" |
| + (" <-- CONCENTRATED" if max(tops) > 0.30 else "")) |
| if rngs: |
| print(f"SPAN block_absmax/rms max={max(rngs):.2f}" |
| + (" <-- OUTLIER-DOMINATED" if max(rngs) > 8.0 else "")) |
|
|
| |
| try: |
| names = list(inspect.signature(REF).parameters) |
| except (TypeError, ValueError): |
| names = [] |
| base = MK(*shp, seed=SEEDS[0]) |
| for i, nm in enumerate(names): |
| if i >= len(base) or not torch.is_tensor(base[i]) or not base[i].is_floating_point(): |
| continue |
| e2, nel = [], 0 |
| for s in SEEDS[:20]: |
| a = list(MK(*shp, seed=s)) |
| ref = floats(REF(*a)) |
| if not ref: |
| break |
| nel = a[i].numel() |
| a[i] = a[i].to(torch.bfloat16).to(base[i].dtype) |
| alt = floats(REF(*a)) |
| e2.append(rel(alt[0], ref[0])) |
| if not e2 or max(e2) == 0: |
| continue |
| gran = "PER-TENSOR" if nel == 1 else f"n={nel}" |
| risky = nel == 1 and TOL and max(e2) > TOL / 10 and max(e2) / max(min(e2), 1e-30) > 10 |
| print(f"SPAN arg {nm:18s} {gran:12s} bf16-round E {min(e2):.2e}..{max(e2):.2e}" |
| + (" <-- SCALAR SEED LOTTERY" if risky else "")) |
| print("SPAN DONE") |
|
|