File size: 9,976 Bytes
995e752
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""quantized-optimizer-state verifier — correctness gate + achieved-GB/s SPEED LEADERBOARD (uncapped).

    reward = 0                                     if the submission is incorrect
    reward = geomean over graded shapes of GB/s otherwise

GENERATED by _factory/build.py — do not edit here; edit the spec and regenerate.

There is no gold solution and no oracle: the score is an absolute hardware metric, so it is hardware-portable
by construction and nothing has to be vendored, sealed, or re-benchmarked.

CORRECTNESS is a hard gate, checked against an INDEPENDENT (embedded) copy of the reference at every graded
shape including the timed ones, so editing /app/reference.py cannot affect grading and a fast wrong kernel
scores 0.

ANTI-CHEAT on the timing path: every timed rep runs on FRESHLY generated inputs, and the output of the last
timed rep is itself validated against the reference for those exact inputs. A submission that memoizes a
result and replays it fails the gate instead of posting an inflated number. Warm-up runs on a separate
throwaway input set, so ordinary shape-keyed JIT/autotune caching is not penalised.

WORK is attributed by a CANONICAL formula that depends only on the shape, never on the implementation, so all
submissions are credited identically and the ranking is a pure speed ranking.
"""
import importlib.util
import json
import math
import os
import sys
import traceback

import torch

REWARD_DIR = "/logs/verifier"
MODULE_PATH = "/app/qadam.py"
TOL = 4e-05
NAMES = ('params_out', 'm_out', 'v_out', 'm_absmax_out', 'v_absmax_out')

GRADER_SHAPES = [(146484,), (97656,), (122070,), (136718,), (107421,)]
CORRECT_SHAPES = [(7,), (13,), (129,), (61,)]

sys.path.insert(0, "/app")

def canonical_work(NB):
    """BYTES attributed to one 8-bit AdamW step, from the SHAPE ALONE.

    N = NB*2048 parameters. Per parameter: read params (2), grads (2), both moment codes (1 + 1) = 6, and
    write params (2) plus both dequantised moments (4 + 4) = 10. The (N/2048,) absmax vectors are 1/2048 of
    the traffic and are not counted. 16 bytes per parameter; this is a memory-bound kernel, so the score is
    achieved bandwidth against that fixed byte count.
    """
    return 16 * NB * 2048

BLOCK = 2048            # quantisation block: one fp32 absmax per 2048 consecutive parameters


def _requantise(x, qmap):
    """x -> (dequantised round trip, per-block absmax). Nearest entry of the ascending 256-point map."""
    nb = x.numel() // BLOCK
    xb = x.view(nb, BLOCK)
    absmax = xb.abs().amax(-1)                                  # the NEW scale of this block
    c = xb / absmax.clamp(min=1e-30).unsqueeze(-1)              # normalised into the map's range
    mid = (qmap[:-1] + qmap[1:]) * 0.5                          # 255 midpoints, ascending
    code = torch.bucketize(c, mid)                              # index of the nearest map entry
    return (qmap[code] * absmax.unsqueeze(-1)).reshape(-1), absmax


def _ref(params, grads, m_code, m_absmax, v_code, v_absmax, qmap1, qmap2, step,
                         lr=1e-3, beta1=0.9, beta2=0.999, eps=1e-8, wd=0.01):
    """8-bit blockwise AdamW, in fp32.

    Correct and simple — it is the numerical SPECIFICATION, not a performance target. Every line
    materialises another full-size fp32 temporary in HBM.
    """
    m = qmap1[m_code.long()] * m_absmax.repeat_interleave(BLOCK)     # dequantise the first moment
    v = qmap2[v_code.long()] * v_absmax.repeat_interleave(BLOCK)     # dequantise the second moment
    g = grads.float()

    m_new = beta1 * m + (1.0 - beta1) * g
    v_new = beta2 * v + (1.0 - beta2) * g * g

    bc1 = 1.0 - beta1 ** step
    bc2 = 1.0 - beta2 ** step
    denom = (v_new / bc2).sqrt() + eps
    upd = (lr / bc1) * m_new / denom
    p_out = params.float() * (1.0 - lr * wd) - upd                   # DECOUPLED weight decay

    m_out, m_absmax_out = _requantise(m_new, qmap1)                  # the state that gets stored back
    v_out, v_absmax_out = _requantise(v_new, qmap2)
    return p_out.to(torch.bfloat16), m_out, v_out, m_absmax_out, v_absmax_out

def _mk(NB, seed):
    """A parameter buffer of NB blocks of 2048, with its 8-bit moment state already in the quantised form
    the reference must dequantise. The maps are the fixed nonlinear (cubic) maps the optimiser ships with:
    fine resolution near zero, coarse near the block maximum."""
    gen = torch.Generator(device="cuda").manual_seed(seed)
    N = NB * 2048

    t = (torch.arange(256, device="cuda", dtype=torch.float32) - 127.5) / 127.5
    qmap1 = t.sign() * t.abs() ** 3                                  # signed, ascending, [-1, 1]
    qmap2 = (torch.arange(256, device="cuda", dtype=torch.float32) / 255.0) ** 3   # unsigned, [0, 1]

    params = (torch.randn(N, device="cuda", generator=gen) * 0.02).to(torch.bfloat16)
    grads = (torch.randn(N, device="cuda", generator=gen) * 1e-3).to(torch.bfloat16)
    m_code = torch.randint(0, 256, (N,), device="cuda", dtype=torch.uint8, generator=gen)
    # v_code starts at 1, not 0: qmap2[0] is exactly 0, so a zero code with a ~0 gradient makes
    # v_new underflow and the AdamW denominator collapse to eps=1e-8, giving that element an
    # update ~1e4x typical. Eight such elements then carried 86% of the output tensor's energy,
    # so the relative-Frobenius gate was effectively reading eight numbers. A trained model's
    # second moment is never exactly zero. With this change the top-8 share drops to 3.1%.
    v_code = torch.randint(1, 256, (N,), device="cuda", dtype=torch.uint8, generator=gen)
    m_absmax = (1e-3 * (0.5 + torch.rand(NB, device="cuda", generator=gen))).float()
    v_absmax = (1e-6 * (0.5 + torch.rand(NB, device="cuda", generator=gen))).float()
    step = 137
    return (params, grads, m_code, m_absmax, v_code, v_absmax, qmap1, qmap2, step)


def _check(out, ref):
    """-> (ok, value, msg). value = MAX relative error across the returned tuple."""
    if out is None or len(out) != len(NAMES):
        return False, 1.0, f"expected a {len(NAMES)}-tuple {NAMES}"
    per = []
    for n, a, b in zip(NAMES, out, ref):
        if a is None or tuple(a.shape) != tuple(b.shape):
            return False, 1.0, f"{n} bad shape"
        if b.dtype in (torch.int8, torch.int16, torch.int32, torch.int64, torch.uint8, torch.bool):
            # exact: .float() is lossy above 2**24 and would let distinct large ids compare equal
            bad = int((a != b).sum())
            if bad:
                return False, 1.0, f"{n}: {bad} elements differ"
            continue
        per.append((n, float((a.float() - b.float()).norm() / (b.float().norm() + 1e-12))))
    if not per:
        return True, 0.0, "all integer outputs exact"
    wn, wv = max(per, key=lambda x: x[1])
    return wv <= TOL, wv, f"worst {wn} {wv:.2e}"


def _bench_fresh(fn, mkargs, reps=5, warm=3):
    """Time `fn` on FRESH inputs every rep -> (min_seconds, timed_ok). See the module docstring."""
    wargs = mkargs(0)
    for _ in range(warm):
        fn(*wargs)
    torch.cuda.synchronize()
    del wargs
    torch.cuda.empty_cache()

    best, timed_ok = float("inf"), True
    for i in range(reps):
        args = mkargs(10_000 + i)
        s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
        s.record()
        out = fn(*args)
        e.record()
        torch.cuda.synchronize()
        best = min(best, s.elapsed_time(e))
        if i == reps - 1:
            timed_ok = _check(out, _ref(*args))[0]
        del args, out
        torch.cuda.empty_cache()
    return best / 1e3, timed_ok


def _geomean(xs):
    return math.exp(sum(math.log(max(v, 1e-9)) for v in xs) / len(xs)) if xs else 0.0


def main():
    details, correct_gate, geo = {}, False, 0.0
    try:
        spec = importlib.util.spec_from_file_location("submission", MODULE_PATH)
        m = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(m)
        fn = m.quantized_adamw_step

        corr_ok, msg = True, ""
        for i, shp in enumerate(CORRECT_SHAPES):
            args = _mk(*shp, seed=10 + i)
            ok, val, m_ = _check(fn(*args), _ref(*args))
            if not ok:
                corr_ok, msg = False, f"cfg{i} {shp} {m_}"
                break
            del args
            torch.cuda.empty_cache()
        details["correct_msg"] = msg or "all correctness shapes pass"

        vals, per_shape, perf_ok = [], [], corr_ok
        for i, shp in enumerate(GRADER_SHAPES):
            args = _mk(*shp, seed=100 + i)
            ok, val, m_ = _check(fn(*args), _ref(*args))
            if not ok:
                perf_ok = False
            del args
            torch.cuda.empty_cache()
            t, timed_ok = _bench_fresh(fn, lambda s, _p=shp: _mk(*_p, seed=s))
            if not timed_ok:
                perf_ok = False
            v = canonical_work(*shp) / t / 2**30 if t > 0 else 0.0
            vals.append(v)
            per_shape.append({"shape": list(shp), "gbps": round(v, 3), "ms": round(t * 1e3, 3),
                              "check": m_, "timed_ok": timed_ok})
        geo = _geomean(vals)
        details.update(per_shape=per_shape, geomean=round(geo, 4), perf_size_ok=perf_ok)
        correct_gate = corr_ok and perf_ok
    except Exception as e:
        details["error"] = f"{e.__class__.__name__}: {e}"[:220]
        details["trace"] = traceback.format_exc()[-800:]

    reward = round(geo, 4) if correct_gate else 0.0
    os.makedirs(REWARD_DIR, exist_ok=True)
    json.dump({"reward": reward, "correct": 1.0 if correct_gate else 0.0,
               "geomean": round(geo, 4), "metric": "GB/s (geomean over graded shapes)"},
              open(f"{REWARD_DIR}/reward.json", "w"), indent=2)
    open(f"{REWARD_DIR}/reward.txt", "w").write(str(reward))
    json.dump(details, open(f"{REWARD_DIR}/details.json", "w"), indent=2, default=str)
    print("reward:", reward, "GB/s | correct:", 1.0 if correct_gate else 0.0)


main()