File size: 7,210 Bytes
ef0b4ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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")

# legacy graders touch __file__ at module level; exec of a string has neither
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")

# Reference discovery. Factory graders embed it as _ref; legacy hand-written graders keep it under the
# kernel's own name. Pick the top-level function whose arity matches what _mk returns.
REF = V.get("_ref")
# preferred: the runner tells us the graded function's name (same discovery validate.sh uses)
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}")
# legacy hand-written graders name their embedded reference ref_fp32 / ref_mla / ref_*
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}")

# ---- 1/3/4: seed spread of a bf16-execution twin, concentration, dynamic range ----------------
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 ""))

# ---- 2: per-argument scale-rounding sensitivity, with granularity -----------------------------
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")