Reorganise: group 313 tasks into 17 families under tasks/, generators under tools/ (part 10)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tasks/video-sparse-attention/sparse-attn-mask-build-3d/tests/verify_env.py +213 -0
- tasks/video-sparse-attention/sparse-block-worklist-build/RUN.md +42 -0
- tasks/video-sparse-attention/sparse-block-worklist-build/environment/CLAUDE.md +25 -0
- tasks/video-sparse-attention/sparse-block-worklist-build/environment/Dockerfile +41 -0
- tasks/video-sparse-attention/sparse-block-worklist-build/environment/PROCESS_MANAGEMENT.md +96 -0
- tasks/video-sparse-attention/sparse-block-worklist-build/environment/docker-compose.yaml +18 -0
- tasks/video-sparse-attention/sparse-block-worklist-build/environment/measure.py +141 -0
- tasks/video-sparse-attention/sparse-block-worklist-build/environment/reference.py +39 -0
- tasks/video-sparse-attention/sparse-block-worklist-build/environment/restrict-network.sh +52 -0
- tasks/video-sparse-attention/sparse-block-worklist-build/environment/worklist.py +29 -0
- tasks/video-sparse-attention/sparse-block-worklist-build/instruction.md +207 -0
- tasks/video-sparse-attention/sparse-block-worklist-build/task.toml +38 -0
- tasks/video-sparse-attention/sparse-block-worklist-build/tests/test.sh +5 -0
- tasks/video-sparse-attention/sparse-block-worklist-build/tests/verify_env.py +219 -0
- tasks/video-sparse-attention/spatial-window-temporal-global/RUN.md +42 -0
- tasks/video-sparse-attention/spatial-window-temporal-global/environment/CLAUDE.md +25 -0
- tasks/video-sparse-attention/spatial-window-temporal-global/environment/Dockerfile +41 -0
- tasks/video-sparse-attention/spatial-window-temporal-global/environment/PROCESS_MANAGEMENT.md +96 -0
- tasks/video-sparse-attention/spatial-window-temporal-global/environment/docker-compose.yaml +18 -0
- tasks/video-sparse-attention/spatial-window-temporal-global/environment/measure.py +112 -0
- tasks/video-sparse-attention/spatial-window-temporal-global/environment/reference.py +62 -0
- tasks/video-sparse-attention/spatial-window-temporal-global/environment/restrict-network.sh +52 -0
- tasks/video-sparse-attention/spatial-window-temporal-global/environment/win_global.py +26 -0
- tasks/video-sparse-attention/spatial-window-temporal-global/instruction.md +218 -0
- tasks/video-sparse-attention/spatial-window-temporal-global/task.toml +38 -0
- tasks/video-sparse-attention/spatial-window-temporal-global/tests/test.sh +5 -0
- tasks/video-sparse-attention/spatial-window-temporal-global/tests/verify_env.py +213 -0
- tasks/video-sparse-attention/sta-backward/RUN.md +42 -0
- tasks/video-sparse-attention/sta-backward/environment/CLAUDE.md +25 -0
- tasks/video-sparse-attention/sta-backward/environment/Dockerfile +41 -0
- tasks/video-sparse-attention/sta-backward/environment/PROCESS_MANAGEMENT.md +96 -0
- tasks/video-sparse-attention/sta-backward/environment/docker-compose.yaml +18 -0
- tasks/video-sparse-attention/sta-backward/environment/measure.py +151 -0
- tasks/video-sparse-attention/sta-backward/environment/reference.py +76 -0
- tasks/video-sparse-attention/sta-backward/environment/restrict-network.sh +52 -0
- tasks/video-sparse-attention/sta-backward/environment/sta_bwd.py +28 -0
- tasks/video-sparse-attention/sta-backward/instruction.md +228 -0
- tasks/video-sparse-attention/sta-backward/task.toml +38 -0
- tasks/video-sparse-attention/sta-backward/tests/test.sh +5 -0
- tasks/video-sparse-attention/sta-backward/tests/verify_env.py +266 -0
- tasks/video-sparse-attention/sta-ragged-tile-boundary/RUN.md +42 -0
- tasks/video-sparse-attention/sta-ragged-tile-boundary/environment/CLAUDE.md +25 -0
- tasks/video-sparse-attention/sta-ragged-tile-boundary/environment/Dockerfile +41 -0
- tasks/video-sparse-attention/sta-ragged-tile-boundary/environment/PROCESS_MANAGEMENT.md +96 -0
- tasks/video-sparse-attention/sta-ragged-tile-boundary/environment/docker-compose.yaml +18 -0
- tasks/video-sparse-attention/sta-ragged-tile-boundary/environment/measure.py +128 -0
- tasks/video-sparse-attention/sta-ragged-tile-boundary/environment/reference.py +51 -0
- tasks/video-sparse-attention/sta-ragged-tile-boundary/environment/restrict-network.sh +52 -0
- tasks/video-sparse-attention/sta-ragged-tile-boundary/environment/sta_ragged.py +27 -0
- tasks/video-sparse-attention/sta-ragged-tile-boundary/instruction.md +194 -0
tasks/video-sparse-attention/sparse-attn-mask-build-3d/tests/verify_env.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""sparse-attn-mask-build-3d verifier — correctness gate + achieved-GB/s SPEED LEADERBOARD (uncapped).
|
| 2 |
+
|
| 3 |
+
reward = 0 if the submission is incorrect
|
| 4 |
+
reward = geomean over graded shapes of GB/s otherwise
|
| 5 |
+
|
| 6 |
+
GENERATED by _factory/build.py — do not edit here; edit the spec and regenerate.
|
| 7 |
+
|
| 8 |
+
There is no gold solution and no oracle: the score is an absolute hardware metric, so it is hardware-portable
|
| 9 |
+
by construction and nothing has to be vendored, sealed, or re-benchmarked.
|
| 10 |
+
|
| 11 |
+
CORRECTNESS is a hard gate, checked against an INDEPENDENT (embedded) copy of the reference at every graded
|
| 12 |
+
shape including the timed ones, so editing /app/reference.py cannot affect grading and a fast wrong kernel
|
| 13 |
+
scores 0.
|
| 14 |
+
|
| 15 |
+
ANTI-CHEAT on the timing path: every timed rep runs on FRESHLY generated inputs, and the output of the last
|
| 16 |
+
timed rep is itself validated against the reference for those exact inputs. A submission that memoizes a
|
| 17 |
+
result and replays it fails the gate instead of posting an inflated number. Warm-up runs on a separate
|
| 18 |
+
throwaway input set, so ordinary shape-keyed JIT/autotune caching is not penalised.
|
| 19 |
+
|
| 20 |
+
WORK is attributed by a CANONICAL formula that depends only on the shape, never on the implementation, so all
|
| 21 |
+
submissions are credited identically and the ranking is a pure speed ranking.
|
| 22 |
+
"""
|
| 23 |
+
import importlib.util
|
| 24 |
+
import json
|
| 25 |
+
import math
|
| 26 |
+
import os
|
| 27 |
+
import sys
|
| 28 |
+
import traceback
|
| 29 |
+
|
| 30 |
+
import torch
|
| 31 |
+
|
| 32 |
+
REWARD_DIR = "/logs/verifier"
|
| 33 |
+
MODULE_PATH = "/app/mask_build.py"
|
| 34 |
+
TOL = 0.015
|
| 35 |
+
|
| 36 |
+
GRADER_SHAPES = [(1, 32, 48, 80, 24, 128, 2, 4, 4), (1, 20, 48, 80, 40, 128, 2, 4, 8), (1, 32, 48, 80, 16, 128, 2, 2, 8), (1, 24, 48, 80, 24, 64, 2, 4, 4), (2, 16, 48, 80, 24, 128, 2, 4, 4)]
|
| 37 |
+
CORRECT_SHAPES = [(1, 8, 16, 32, 4, 64, 2, 4, 8), (2, 6, 12, 24, 4, 64, 2, 4, 8), (1, 12, 16, 32, 8, 128, 3, 4, 8), (1, 10, 10, 20, 4, 64, 2, 2, 4), (1, 9, 12, 20, 4, 128, 3, 4, 5)]
|
| 38 |
+
|
| 39 |
+
sys.path.insert(0, "/app")
|
| 40 |
+
|
| 41 |
+
def canonical_work(B, F, Hh, Ww, NH, D, TF, TH, TW):
|
| 42 |
+
"""BYTES attributed to one call, from the SHAPE ALONE.
|
| 43 |
+
|
| 44 |
+
Read q and k once (bf16) to pool them, write the (B, NH, NT, NT) fp32 score map once. The pooled
|
| 45 |
+
tensors, the (NT, NT) bias and the softmax state are tiny by comparison and stay on chip. The output
|
| 46 |
+
dominates: this is a bandwidth kernel, so the score is achieved bandwidth against this fixed byte count.
|
| 47 |
+
"""
|
| 48 |
+
ntf, nth, ntw = F // TF, Hh // TH, Ww // TW
|
| 49 |
+
NT = ntf * nth * ntw
|
| 50 |
+
T = F * Hh * Ww
|
| 51 |
+
return 2 * (B * T * NH * D * 2) + B * NH * NT * NT * 4
|
| 52 |
+
|
| 53 |
+
def _ref(q, k, latent, tile, decay, scale=None):
|
| 54 |
+
"""3D tile pooling + block-score GEMM + distance decay + row softmax, in fp32.
|
| 55 |
+
|
| 56 |
+
Correct and simple — it is the numerical SPECIFICATION, not a performance target. It permutes the whole
|
| 57 |
+
sequence into tile-major order, materialises the pooled tensors and the full (B, NH, NT, NT) bias, and
|
| 58 |
+
then softmaxes.
|
| 59 |
+
"""
|
| 60 |
+
B, T, NH, D = q.shape
|
| 61 |
+
F, Hh, Ww = latent
|
| 62 |
+
tf, th, tw = tile
|
| 63 |
+
lf, lh, lw = decay
|
| 64 |
+
ntf, nth, ntw = F // tf, Hh // th, Ww // tw
|
| 65 |
+
NT = ntf * nth * ntw
|
| 66 |
+
TS = tf * th * tw
|
| 67 |
+
if scale is None:
|
| 68 |
+
scale = D ** -0.5
|
| 69 |
+
dev = q.device
|
| 70 |
+
|
| 71 |
+
def pool(x):
|
| 72 |
+
return (x.view(B, ntf, tf, nth, th, ntw, tw, NH, D)
|
| 73 |
+
.permute(0, 1, 3, 5, 7, 2, 4, 6, 8)
|
| 74 |
+
.reshape(B, NT, NH, TS, D).float().mean(dim=3)) # (B, NT, NH, D)
|
| 75 |
+
|
| 76 |
+
qp, kp = pool(q), pool(k)
|
| 77 |
+
s = torch.einsum("bihd,bjhd->bhij", qp * scale, kp) # (B, NH, NT, NT)
|
| 78 |
+
|
| 79 |
+
a = torch.arange(NT, device=dev)
|
| 80 |
+
ta, tb, tc = a // (nth * ntw), (a // ntw) % nth, a % ntw
|
| 81 |
+
bias = (lf * (ta[:, None] - ta[None, :]).abs()
|
| 82 |
+
+ lh * (tb[:, None] - tb[None, :]).abs()
|
| 83 |
+
+ lw * (tc[:, None] - tc[None, :]).abs()).float() # (NT, NT)
|
| 84 |
+
return torch.softmax(s - bias, dim=-1)
|
| 85 |
+
|
| 86 |
+
def _mk(B, F, Hh, Ww, NH, D, TF, TH, TW, seed):
|
| 87 |
+
import math
|
| 88 |
+
gen = torch.Generator(device="cuda").manual_seed(seed)
|
| 89 |
+
T = F * Hh * Ww
|
| 90 |
+
dev = "cuda"
|
| 91 |
+
R = 12
|
| 92 |
+
AMP = 2.6
|
| 93 |
+
# Realistic activations: a smooth low-frequency 3D field plus white noise. Real latent activations vary
|
| 94 |
+
# slowly across the volume, which is exactly why tile-mean pooling is an informative summary at all --
|
| 95 |
+
# pooling white noise would leave the block scores at zero and the map would be pure distance decay.
|
| 96 |
+
ax = [torch.arange(n, device=dev, dtype=torch.float32) / n for n in (F, Hh, Ww)]
|
| 97 |
+
kk = torch.randint(0, 3, (3, R), device=dev, generator=gen).float()
|
| 98 |
+
ph = torch.rand(R, device=dev, generator=gen) * (2 * math.pi)
|
| 99 |
+
ang = (kk[0].view(R, 1, 1, 1) * ax[0].view(1, F, 1, 1)
|
| 100 |
+
+ kk[1].view(R, 1, 1, 1) * ax[1].view(1, 1, Hh, 1)
|
| 101 |
+
+ kk[2].view(R, 1, 1, 1) * ax[2].view(1, 1, 1, Ww)) * (2 * math.pi) + ph.view(R, 1, 1, 1)
|
| 102 |
+
basis = torch.cos(ang).reshape(R, T).t().contiguous() # (T, R)
|
| 103 |
+
def field():
|
| 104 |
+
w = torch.randn(NH, R, D, device=dev, generator=gen) * (AMP / R ** 0.5)
|
| 105 |
+
out = torch.empty(B, T, NH, D, device=dev, dtype=torch.bfloat16)
|
| 106 |
+
step = max(1, 8_000_000 // max(1, NH * D))
|
| 107 |
+
for s0 in range(0, T, step):
|
| 108 |
+
e0 = min(T, s0 + step)
|
| 109 |
+
x = torch.einsum("tr,hrd->thd", basis[s0:e0], w).unsqueeze(0)
|
| 110 |
+
x = x + torch.randn(B, e0 - s0, NH, D, device=dev, generator=gen)
|
| 111 |
+
out[:, s0:e0] = x.bfloat16()
|
| 112 |
+
return out
|
| 113 |
+
return field(), field(), (F, Hh, Ww), (TF, TH, TW), (0.20, 0.05, 0.05)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def _is_exact(t):
|
| 117 |
+
"""Integer/bool tensors are compared EXACTLY: .float() is lossy above 2**24, so two distinct large
|
| 118 |
+
ids (page ids, token ids, indices) can compare equal and let a wrong kernel pass."""
|
| 119 |
+
return t.dtype in (torch.int8, torch.int16, torch.int32, torch.int64, torch.uint8, torch.bool)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def _check(out, ref):
|
| 123 |
+
"""-> (ok, value, msg). Exact for integer/bool; relative Frobenius error otherwise."""
|
| 124 |
+
if out is None or tuple(out.shape) != tuple(ref.shape):
|
| 125 |
+
return False, 1.0, "bad/None shape"
|
| 126 |
+
if _is_exact(ref):
|
| 127 |
+
bad = int((out != ref).sum())
|
| 128 |
+
return bad == 0, float(bad), ("exact match" if bad == 0 else f"{bad} elements differ")
|
| 129 |
+
e = float((out.float() - ref.float()).norm() / (ref.float().norm() + 1e-12))
|
| 130 |
+
return e <= TOL, e, f"relerr {e:.2e}"
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def _bench_fresh(fn, mkargs, reps=5, warm=3):
|
| 134 |
+
"""Time `fn` on FRESH inputs every rep -> (min_seconds, timed_ok). See the module docstring."""
|
| 135 |
+
wargs = mkargs(0)
|
| 136 |
+
for _ in range(warm):
|
| 137 |
+
fn(*wargs)
|
| 138 |
+
torch.cuda.synchronize()
|
| 139 |
+
del wargs
|
| 140 |
+
torch.cuda.empty_cache()
|
| 141 |
+
|
| 142 |
+
best, timed_ok = float("inf"), True
|
| 143 |
+
for i in range(reps):
|
| 144 |
+
args = mkargs(10_000 + i)
|
| 145 |
+
s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
|
| 146 |
+
s.record()
|
| 147 |
+
out = fn(*args)
|
| 148 |
+
e.record()
|
| 149 |
+
torch.cuda.synchronize()
|
| 150 |
+
best = min(best, s.elapsed_time(e))
|
| 151 |
+
if i == reps - 1:
|
| 152 |
+
timed_ok = _check(out, _ref(*args))[0]
|
| 153 |
+
del args, out
|
| 154 |
+
torch.cuda.empty_cache()
|
| 155 |
+
return best / 1e3, timed_ok
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def _geomean(xs):
|
| 159 |
+
return math.exp(sum(math.log(max(v, 1e-9)) for v in xs) / len(xs)) if xs else 0.0
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def main():
|
| 163 |
+
details, correct_gate, geo = {}, False, 0.0
|
| 164 |
+
try:
|
| 165 |
+
spec = importlib.util.spec_from_file_location("submission", MODULE_PATH)
|
| 166 |
+
m = importlib.util.module_from_spec(spec)
|
| 167 |
+
spec.loader.exec_module(m)
|
| 168 |
+
fn = m.build_block_scores_3d
|
| 169 |
+
|
| 170 |
+
corr_ok, msg = True, ""
|
| 171 |
+
for i, shp in enumerate(CORRECT_SHAPES):
|
| 172 |
+
args = _mk(*shp, seed=10 + i)
|
| 173 |
+
ok, val, m_ = _check(fn(*args), _ref(*args))
|
| 174 |
+
if not ok:
|
| 175 |
+
corr_ok, msg = False, f"cfg{i} {shp} {m_}"
|
| 176 |
+
break
|
| 177 |
+
del args
|
| 178 |
+
torch.cuda.empty_cache()
|
| 179 |
+
details["correct_msg"] = msg or "all correctness shapes pass"
|
| 180 |
+
|
| 181 |
+
vals, per_shape, perf_ok = [], [], corr_ok
|
| 182 |
+
for i, shp in enumerate(GRADER_SHAPES):
|
| 183 |
+
args = _mk(*shp, seed=100 + i)
|
| 184 |
+
ok, val, m_ = _check(fn(*args), _ref(*args))
|
| 185 |
+
if not ok:
|
| 186 |
+
perf_ok = False
|
| 187 |
+
del args
|
| 188 |
+
torch.cuda.empty_cache()
|
| 189 |
+
t, timed_ok = _bench_fresh(fn, lambda s, _p=shp: _mk(*_p, seed=s))
|
| 190 |
+
if not timed_ok:
|
| 191 |
+
perf_ok = False
|
| 192 |
+
v = canonical_work(*shp) / t / 2**30 if t > 0 else 0.0
|
| 193 |
+
vals.append(v)
|
| 194 |
+
per_shape.append({"shape": list(shp), "gbps": round(v, 3), "ms": round(t * 1e3, 3),
|
| 195 |
+
"check": m_, "timed_ok": timed_ok})
|
| 196 |
+
geo = _geomean(vals)
|
| 197 |
+
details.update(per_shape=per_shape, geomean=round(geo, 4), perf_size_ok=perf_ok)
|
| 198 |
+
correct_gate = corr_ok and perf_ok
|
| 199 |
+
except Exception as e:
|
| 200 |
+
details["error"] = f"{e.__class__.__name__}: {e}"[:220]
|
| 201 |
+
details["trace"] = traceback.format_exc()[-800:]
|
| 202 |
+
|
| 203 |
+
reward = round(geo, 4) if correct_gate else 0.0
|
| 204 |
+
os.makedirs(REWARD_DIR, exist_ok=True)
|
| 205 |
+
json.dump({"reward": reward, "correct": 1.0 if correct_gate else 0.0,
|
| 206 |
+
"geomean": round(geo, 4), "metric": "GB/s (geomean over graded shapes)"},
|
| 207 |
+
open(f"{REWARD_DIR}/reward.json", "w"), indent=2)
|
| 208 |
+
open(f"{REWARD_DIR}/reward.txt", "w").write(str(reward))
|
| 209 |
+
json.dump(details, open(f"{REWARD_DIR}/details.json", "w"), indent=2, default=str)
|
| 210 |
+
print("reward:", reward, "GB/s | correct:", 1.0 if correct_gate else 0.0)
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
main()
|
tasks/video-sparse-attention/sparse-block-worklist-build/RUN.md
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Running `sparse-block-worklist-build`
|
| 2 |
+
|
| 3 |
+
Between the mask builder and the attention kernel sits the piece nobody writes about and everybody needs: turning a per-head tile BITMAP into the flat work list a block-sparse attention kernel actually consumes. Popcount every row, prefix-sum 300k rows into CSR offsets, compact the live (query tile, key tile) pairs in row-major order, and cut the result into equal-work slices for a persistent grid. It is a scan and a stream compaction over a gigabyte of pairs, and it runs before every attention call.
|
| 4 |
+
|
| 5 |
+
| | |
|
| 6 |
+
|---|---|
|
| 7 |
+
| **Task id** | `mle-bench/sparse-block-worklist-build` |
|
| 8 |
+
| **Group** | `kernel-generation` |
|
| 9 |
+
| **GPUs** | 1 |
|
| 10 |
+
| **Agent edits** | `/app/worklist.py` |
|
| 11 |
+
| **Score** | achieved **GB/s** (uncapped speed leaderboard), `0` if incorrect |
|
| 12 |
+
| **Grade output** | `tests/test.sh` -> `/logs/verifier/reward.json` |
|
| 13 |
+
|
| 14 |
+
## Run through harbor
|
| 15 |
+
|
| 16 |
+
```bash
|
| 17 |
+
harbor run --dataset-path kernel-generation/kernels/sparse-block-worklist-build --task-name sparse-block-worklist-build \
|
| 18 |
+
--agent claude-code --model anthropic/claude-opus-4-1 -e docker
|
| 19 |
+
```
|
| 20 |
+
|
| 21 |
+
## Run manually
|
| 22 |
+
|
| 23 |
+
```bash
|
| 24 |
+
cd kernel-generation/kernels/sparse-block-worklist-build
|
| 25 |
+
docker build -t sparse-block-worklist-build environment/
|
| 26 |
+
docker run -d --name v --gpus '"device=0"' --shm-size=8g --entrypoint sleep sparse-block-worklist-build infinity
|
| 27 |
+
docker cp tests v:/tests && docker exec v bash /tests/test.sh # untouched start -> reward 0.0
|
| 28 |
+
docker rm -f v
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
Use an **idle** GPU: the score is a timing measurement.
|
| 32 |
+
|
| 33 |
+
## Design
|
| 34 |
+
|
| 35 |
+
Correctness is a hard gate; the score is an absolute hardware metric (GB/s), so the task is
|
| 36 |
+
hardware-portable and needs no gold solution, no oracle, and nothing vendored or sealed.
|
| 37 |
+
|
| 38 |
+
Anti-cheat is structural: the image holds only the permitted toolchain and has no internet; the grader is
|
| 39 |
+
copied in at grade time with its own private copy of the reference; and every timed rep runs on fresh inputs
|
| 40 |
+
with the timed output itself validated, so memoize-and-replay fails the gate.
|
| 41 |
+
|
| 42 |
+
Generated by `_factory/build.py` — edit the spec and regenerate rather than editing this task by hand.
|
tasks/video-sparse-attention/sparse-block-worklist-build/environment/CLAUDE.md
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Working in this environment
|
| 2 |
+
|
| 3 |
+
## ⚠️ Stop background processes without killing yourself
|
| 4 |
+
|
| 5 |
+
You are launched as `claude --print -- '<the task instruction>'`, so the task text — including the
|
| 6 |
+
file names and commands it mentions — is on **your own** process's command line. Any command that
|
| 7 |
+
finds processes by **matching that text** (`pkill -f …`, `pgrep -f … | xargs kill`, a `/proc`
|
| 8 |
+
cmdline scan, `fuser -k`, `killall`) can match and **kill the agent itself**, ending your run
|
| 9 |
+
(`NonZeroAgentExitCodeError`) and grading you on unfinished work.
|
| 10 |
+
|
| 11 |
+
This bites whenever you background something and later stop/restart it — a **server**, a long
|
| 12 |
+
**build** or **training run**, or an **ncu / nsys profiling** session.
|
| 13 |
+
|
| 14 |
+
**Always** manage a background process by its **exact recorded PID**, never by a name pattern:
|
| 15 |
+
|
| 16 |
+
```bash
|
| 17 |
+
nohup <your command> > /tmp/job.log 2>&1 & echo $! > /tmp/job.pid # start + record the PID
|
| 18 |
+
kill "$(cat /tmp/job.pid)"; sleep 3 # stop (SIGTERM); -9 only if needed
|
| 19 |
+
```
|
| 20 |
+
|
| 21 |
+
Use `setsid` and kill the process **group** (`kill -- -"$(cat /tmp/job.pid)"`) if it spawns children.
|
| 22 |
+
If you must enumerate processes, match a **unique token that is NOT anywhere in this prompt** and
|
| 23 |
+
**exclude any cmdline containing `claude` or `--print`** — `pgrep -af`, and look before you kill.
|
| 24 |
+
|
| 25 |
+
Full details + safe recipes: **`/app/PROCESS_MANAGEMENT.md`**.
|
tasks/video-sparse-attention/sparse-block-worklist-build/environment/Dockerfile
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Kernel-generation task: Write a fast block-sparse work-list builder (bitmap -> CSR + balanced partition)
|
| 2 |
+
#
|
| 3 |
+
# Between the mask builder and the attention kernel sits the piece nobody writes about and everybody needs: turning a per-head tile BITMAP into the flat work list a block-sparse attention kernel actually consumes. Popcount every row, prefix-sum 300k rows into CSR offsets, compact the live (query tile, key tile) pairs in row-major order, and cut the result into equal-work slices for a persistent grid. It is a scan and a stream compaction over a gigabyte of pairs, and it runs before every attention call.
|
| 4 |
+
#
|
| 5 |
+
# SCORING: correctness is a hard gate; the score is achieved GB/s (uncapped leaderboard, 0 if wrong).
|
| 6 |
+
# There is no gold solution and no oracle, so nothing has to be vendored or sealed.
|
| 7 |
+
#
|
| 8 |
+
# TOOLCHAIN POLICY: the agent writes the kernel with Triton (+Gluon), CUDA C++ via nvcc, CUTLASS headers, or
|
| 9 |
+
# the CuTe DSL. Enforcement is by ABSENCE, not by scanning: only the permitted toolchain is installed and
|
| 10 |
+
# there is no internet, so nothing else can be obtained.
|
| 11 |
+
#
|
| 12 |
+
# GENERATED by _factory/build.py.
|
| 13 |
+
FROM pytorch/pytorch:2.11.0-cuda12.8-cudnn9-devel
|
| 14 |
+
|
| 15 |
+
# NOTE: every heavy layer comes FIRST and depends only on {base_image, pip_extra}, so all tasks in this
|
| 16 |
+
# lane share the same cached layers. The task-specific COPYs are LAST. Do not reorder.
|
| 17 |
+
RUN pip install --break-system-packages --no-cache-dir einops nvidia-cutlass-dsl && \
|
| 18 |
+
apt-get update && apt-get install -y --no-install-recommends iptables iproute2 curl ca-certificates build-essential git && \
|
| 19 |
+
curl -LsSf https://astral.sh/uv/install.sh | sh && \
|
| 20 |
+
/root/.local/bin/uv tool install mini-swe-agent
|
| 21 |
+
# header-only CUTLASS for the agent's CUDA/CuTe route
|
| 22 |
+
RUN git clone --depth 1 https://github.com/NVIDIA/cutlass /opt/cutlass && rm -rf /opt/cutlass/.git
|
| 23 |
+
# pre-bake Claude Code; harbor's claude_code.install() skips when present
|
| 24 |
+
RUN curl -fsSL https://deb.nodesource.com/setup_22.x | bash - && \
|
| 25 |
+
apt-get install -y nodejs procps && \
|
| 26 |
+
npm install -g @anthropic-ai/claude-code && claude --version
|
| 27 |
+
ENV PATH=/root/.local/bin:$PATH
|
| 28 |
+
ENV DISABLE_TELEMETRY=1 DISABLE_AUTOUPDATER=1 DISABLE_ERROR_REPORTING=1 CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1
|
| 29 |
+
|
| 30 |
+
COPY restrict-network.sh /app/restrict-network.sh
|
| 31 |
+
RUN chmod +x /app/restrict-network.sh
|
| 32 |
+
# strip apt sources LAST so harbor's post-firewall apt step is a no-op that succeeds
|
| 33 |
+
RUN rm -rf /var/lib/apt/lists/* /etc/apt/sources.list /etc/apt/sources.list.d
|
| 34 |
+
|
| 35 |
+
WORKDIR /app
|
| 36 |
+
COPY CLAUDE.md PROCESS_MANAGEMENT.md /app/
|
| 37 |
+
|
| 38 |
+
# task-specific files LAST so the layers above stay shared across every task
|
| 39 |
+
COPY reference.py /app/reference.py
|
| 40 |
+
COPY measure.py /app/measure.py
|
| 41 |
+
COPY worklist.py /app/worklist.py
|
tasks/video-sparse-attention/sparse-block-worklist-build/environment/PROCESS_MANAGEMENT.md
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Managing background processes — READ THIS before you `kill` anything
|
| 2 |
+
|
| 3 |
+
You may start and stop background processes while iterating — a **server**, a long **build** or
|
| 4 |
+
**training run**, or an **ncu / nsys profiling** session. **The way you stop one can silently kill
|
| 5 |
+
*your own agent process* and end the whole run.** This has happened repeatedly, including via a
|
| 6 |
+
hand-rolled `/proc` scan — not just `pkill`. Read this once and follow the safe recipe.
|
| 7 |
+
|
| 8 |
+
## The trap: matching task text against process command lines
|
| 9 |
+
|
| 10 |
+
You were launched as roughly:
|
| 11 |
+
|
| 12 |
+
```
|
| 13 |
+
claude --print -- '<the entire task instruction text>'
|
| 14 |
+
```
|
| 15 |
+
|
| 16 |
+
The full task instruction is on **your own** process's command line, and it contains the file names
|
| 17 |
+
and commands the task mentions (e.g. `server.py`, `build.sh`, `train.py`, `solution.cu`, `/app/...`).
|
| 18 |
+
So **any** command that finds processes by matching those strings will match — and can kill — **the
|
| 19 |
+
agent itself**:
|
| 20 |
+
|
| 21 |
+
```
|
| 22 |
+
pkill -9 -f "train.py" # matches the claude agent -> kills YOU
|
| 23 |
+
pgrep -f "server.py" | xargs kill # same: the pid list includes claude
|
| 24 |
+
for p in $(pgrep -f build.sh); do kill -9 $p; done # same
|
| 25 |
+
for pid in /proc/*; do case "$(cmdline)" in *solution*) kill -9 $pid;; esac; done # same
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
It is **not about `pkill`** — it is about **matching a string that appears in your prompt**. `pgrep`,
|
| 29 |
+
a `/proc` scan, `fuser`, or `nvidia-smi`-pid loops all have the same failure if the match pattern (or
|
| 30 |
+
the surviving pid list) includes the `claude` process. When you `kill -9` yourself the run dies
|
| 31 |
+
immediately (`NonZeroAgentExitCodeError`) and you are graded on whatever was already in place — usually
|
| 32 |
+
worse than what you were about to finish.
|
| 33 |
+
|
| 34 |
+
## The one safe rule: kill only the exact PID you recorded
|
| 35 |
+
|
| 36 |
+
**Start** a background job and record its PID in a file:
|
| 37 |
+
|
| 38 |
+
```bash
|
| 39 |
+
nohup <your command> > /tmp/job.log 2>&1 &
|
| 40 |
+
echo $! > /tmp/job.pid
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
**Stop / restart** by that exact PID — never by a name pattern:
|
| 44 |
+
|
| 45 |
+
```bash
|
| 46 |
+
kill "$(cat /tmp/job.pid)" 2>/dev/null # SIGTERM: lets it release the GPU / flush cleanly
|
| 47 |
+
sleep 3
|
| 48 |
+
kill -9 "$(cat /tmp/job.pid)" 2>/dev/null # force only if it did not exit
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
If the job spawns workers, run it in its own process group and signal the group by its (negative)
|
| 52 |
+
PGID — still an exact id, never a pattern:
|
| 53 |
+
|
| 54 |
+
```bash
|
| 55 |
+
setsid <your command> > /tmp/job.log 2>&1 < /dev/null & echo $! > /tmp/job.pid
|
| 56 |
+
kill -TERM -- "-$(cat /tmp/job.pid)" 2>/dev/null
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
## If you ever enumerate processes, EXCLUDE the agent
|
| 60 |
+
|
| 61 |
+
Prefer not to. But if you must scan (e.g. hunting a leaked worker), **exclude the `claude` agent and
|
| 62 |
+
your own shell**, and match on a **unique token that is NOT anywhere in this prompt** — give your job
|
| 63 |
+
a unique name and match only that:
|
| 64 |
+
|
| 65 |
+
```bash
|
| 66 |
+
# job named e.g. job_7x3q9 — a token that appears NOWHERE in the task text
|
| 67 |
+
pgrep -af job_7x3q9 | grep -v -E 'claude|--print|pgrep|grep|bash' # LOOK FIRST
|
| 68 |
+
# only kill pids from THIS filtered list, and never a pid whose cmdline contains 'claude' or '--print'
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
Do **not** add a prompt word (a file name, `/app`, `python3`, …) to the pattern "just in case" — that
|
| 72 |
+
single addition re-introduces the self-kill. Match the unique token **only**.
|
| 73 |
+
|
| 74 |
+
## Freeing the GPU without going nuclear
|
| 75 |
+
|
| 76 |
+
If VRAM stays high after you stop a GPU job, the usual cause is a **child process** or a not-yet-
|
| 77 |
+
collected CUDA context — not a stray process you need to hunt across `/proc`. Do this instead of a
|
| 78 |
+
`/proc` sweep:
|
| 79 |
+
|
| 80 |
+
- Kill the job **by its recorded PID / PGID** (above) and `sleep 5–10`; the CUDA context frees after
|
| 81 |
+
the process fully exits.
|
| 82 |
+
- Make the job release cleanly on `SIGTERM` (drop the model / `torch.cuda.empty_cache()` / exit) so a
|
| 83 |
+
single `kill $PID` is enough.
|
| 84 |
+
- Start it in its own group (`setsid`) so `kill -- -$PGID` takes the workers with it.
|
| 85 |
+
- Check with `nvidia-smi` — if a PID still holds memory, `kill` **that exact numeric PID**, after
|
| 86 |
+
confirming its cmdline is **not** `claude` / `--print`.
|
| 87 |
+
|
| 88 |
+
## Rules of thumb
|
| 89 |
+
|
| 90 |
+
- **Never** match a task-prompt string (`server.py`, `train.py`, `build.sh`, `/app`, `python3`, …)
|
| 91 |
+
with `pkill -f`, `pgrep -f`, `killall`, `fuser`, or a `/proc` cmdline scan — they all can hit the
|
| 92 |
+
agent (its argv holds the prompt).
|
| 93 |
+
- **Always** kill a background job by the exact PID from its pidfile (or its PGID).
|
| 94 |
+
- If you must enumerate, match a **unique token not in the prompt** and **exclude `claude` / `--print`
|
| 95 |
+
and your own shell**; `pgrep -af` and look before you kill.
|
| 96 |
+
- `SIGTERM` first for a clean release; `-9` only as a last resort on a specific numeric PID.
|
tasks/video-sparse-attention/sparse-block-worklist-build/environment/docker-compose.yaml
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Anti-cheat firewall overlay, merged on top of Harbor's base compose. Gives the main container
|
| 2 |
+
# NET_ADMIN and runs restrict-network.sh as the entrypoint, so only DNS + the LLM API endpoints are
|
| 3 |
+
# reachable (pypi/github/HF blocked). network_mode stays "public" (see task.toml) — the firewall, not
|
| 4 |
+
# Docker, enforces the allowlist. mini-swe-agent is pre-installed and harbor's patched installer skips
|
| 5 |
+
# the (now-blocked) network install when it is already present.
|
| 6 |
+
services:
|
| 7 |
+
main:
|
| 8 |
+
cap_add:
|
| 9 |
+
- NET_ADMIN
|
| 10 |
+
entrypoint: ["/bin/bash", "/app/restrict-network.sh"]
|
| 11 |
+
environment:
|
| 12 |
+
- ALLOWED_HOSTS=${ALLOWED_HOSTS:-}
|
| 13 |
+
- FIREWORKS_BASE_URL=${FIREWORKS_BASE_URL:-}
|
| 14 |
+
- OPENROUTER_BASE_URL=${OPENROUTER_BASE_URL:-}
|
| 15 |
+
- OPENAI_BASE_URL=${OPENAI_BASE_URL:-}
|
| 16 |
+
- ANTHROPIC_BASE_URL=${ANTHROPIC_BASE_URL:-}
|
| 17 |
+
- LLM_BASE_URL=${LLM_BASE_URL:-}
|
| 18 |
+
- LITELLM_BASE_URL=${LITELLM_BASE_URL:-}
|
tasks/video-sparse-attention/sparse-block-worklist-build/environment/measure.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Self-assessment tool — your correctness + achieved GB/s across a RANGE of shapes.
|
| 2 |
+
|
| 3 |
+
python /app/measure.py # the graded regime
|
| 4 |
+
python /app/measure.py --quick # smaller sizes for fast iteration
|
| 5 |
+
|
| 6 |
+
You are scored on the **geomean achieved GB/s** — NOT one fixed size, and the leaderboard is UNCAPPED
|
| 7 |
+
(higher is always better). The shapes below are a DIFFERENT sample from the same regime the grader uses, so
|
| 8 |
+
optimize for GENERALITY. Work is counted with the same shape-only formula the grader uses, so the number
|
| 9 |
+
printed here is computed exactly as your score is.
|
| 10 |
+
|
| 11 |
+
GENERATED by _factory/build.py.
|
| 12 |
+
"""
|
| 13 |
+
import argparse
|
| 14 |
+
import math
|
| 15 |
+
import sys
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
|
| 19 |
+
sys.path.insert(0, "/app")
|
| 20 |
+
from reference import build_block_worklist as _ref
|
| 21 |
+
from worklist import build_block_worklist as _agent
|
| 22 |
+
|
| 23 |
+
TOL = 0.0
|
| 24 |
+
NAMES = ('counts', 'offsets', 'pairs', 'bucket_row')
|
| 25 |
+
|
| 26 |
+
FULL = [(2, 32, 4096, 4096, 12, 2048), (2, 24, 4096, 4096, 11, 1024), (4, 20, 3200, 3200, 14, 4096), (1, 40, 4608, 4608, 12, 2048), (2, 24, 3840, 3840, 13, 1536)]
|
| 27 |
+
QUICK = [(1, 8, 1024, 1024, 12, 256), (2, 4, 768, 768, 15, 128), (1, 12, 512, 512, 20, 64)]
|
| 28 |
+
|
| 29 |
+
def _live_counts(B, NH, NQ, NK, DEN):
|
| 30 |
+
"""Live key tiles per (batch, head, query tile), from the SHAPE ALONE.
|
| 31 |
+
|
| 32 |
+
About DEN percent of the NK tiles survive, jittered by +-1 per row so the rows are genuinely ragged, and
|
| 33 |
+
always at least 1.
|
| 34 |
+
"""
|
| 35 |
+
out = []
|
| 36 |
+
base = (NK * DEN) // 100
|
| 37 |
+
for b in range(B):
|
| 38 |
+
for h in range(NH):
|
| 39 |
+
for i in range(NQ):
|
| 40 |
+
c = base + ((b * 31 + h * 17 + i * 7) % 3) - 1
|
| 41 |
+
out.append(min(max(c, 1), NK))
|
| 42 |
+
return out
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def canonical_work(B, NH, NQ, NK, DEN, P):
|
| 46 |
+
"""BYTES moved by one call, from the SHAPE ALONE.
|
| 47 |
+
|
| 48 |
+
Read the packed bitmap once (NK/8 bytes per row), write the counts and the CSR offsets (4 bytes per
|
| 49 |
+
row each), and write the compacted pair list (8 bytes per live pair). The live count is fixed by the
|
| 50 |
+
shape, so the pair list has the same length for every submission.
|
| 51 |
+
"""
|
| 52 |
+
R = B * NH * NQ
|
| 53 |
+
L = sum(_live_counts(B, NH, NQ, NK, DEN))
|
| 54 |
+
return R * (NK // 8) + 8 * L + 8 * R + 4 * (P + 1)
|
| 55 |
+
|
| 56 |
+
def _mk(B, NH, NQ, NK, DEN, P, seed):
|
| 57 |
+
gen = torch.Generator(device="cuda").manual_seed(seed)
|
| 58 |
+
cnt = torch.tensor(_live_counts(B, NH, NQ, NK, DEN), device="cuda").view(B, NH, NQ)
|
| 59 |
+
kmax = int(cnt.max().item())
|
| 60 |
+
sh = torch.arange(8, device="cuda", dtype=torch.int32)
|
| 61 |
+
bits = torch.empty(B, NH, NQ, NK // 8, device="cuda", dtype=torch.uint8)
|
| 62 |
+
for b in range(B):
|
| 63 |
+
for h in range(NH):
|
| 64 |
+
r = torch.rand(NQ, NK, device="cuda", generator=gen)
|
| 65 |
+
idx = r.topk(kmax, dim=-1).indices # (NQ, kmax) random distinct columns
|
| 66 |
+
live = torch.arange(kmax, device="cuda").view(1, -1) < cnt[b, h].view(-1, 1)
|
| 67 |
+
m = torch.zeros(NQ, NK, dtype=torch.bool, device="cuda")
|
| 68 |
+
m.scatter_(1, torch.where(live, idx, idx[:, :1]), True) # rank 0 is always live
|
| 69 |
+
bits[b, h] = ((m.view(NQ, NK // 8, 8).to(torch.int32) << sh).sum(-1)).to(torch.uint8)
|
| 70 |
+
return bits, NK, P
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _check(out, ref):
|
| 74 |
+
"""-> (ok, value, msg). value = MAX relative error across the returned tuple."""
|
| 75 |
+
if out is None or len(out) != len(NAMES):
|
| 76 |
+
return False, 1.0, f"expected a {len(NAMES)}-tuple {NAMES}"
|
| 77 |
+
per = []
|
| 78 |
+
for n, a, b in zip(NAMES, out, ref):
|
| 79 |
+
if a is None or tuple(a.shape) != tuple(b.shape):
|
| 80 |
+
return False, 1.0, f"{n} bad shape"
|
| 81 |
+
if b.dtype in (torch.int8, torch.int16, torch.int32, torch.int64, torch.uint8, torch.bool):
|
| 82 |
+
# exact: .float() is lossy above 2**24 and would let distinct large ids compare equal
|
| 83 |
+
bad = int((a != b).sum())
|
| 84 |
+
if bad:
|
| 85 |
+
return False, 1.0, f"{n}: {bad} elements differ"
|
| 86 |
+
continue
|
| 87 |
+
per.append((n, float((a.float() - b.float()).norm() / (b.float().norm() + 1e-12))))
|
| 88 |
+
if not per:
|
| 89 |
+
return True, 0.0, "all integer outputs exact"
|
| 90 |
+
wn, wv = max(per, key=lambda x: x[1])
|
| 91 |
+
return wv <= TOL, wv, f"worst {wn} {wv:.2e}"
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def _bench(fn, reps=8, warm=3):
|
| 95 |
+
for _ in range(warm):
|
| 96 |
+
fn()
|
| 97 |
+
torch.cuda.synchronize()
|
| 98 |
+
best = float("inf")
|
| 99 |
+
for _ in range(reps):
|
| 100 |
+
s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
|
| 101 |
+
s.record()
|
| 102 |
+
fn()
|
| 103 |
+
e.record()
|
| 104 |
+
torch.cuda.synchronize()
|
| 105 |
+
best = min(best, s.elapsed_time(e))
|
| 106 |
+
return best / 1e3
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def main():
|
| 110 |
+
ap = argparse.ArgumentParser()
|
| 111 |
+
ap.add_argument("--quick", action="store_true")
|
| 112 |
+
a = ap.parse_args()
|
| 113 |
+
shapes = QUICK if a.quick else FULL
|
| 114 |
+
print(f"geomean over {len(shapes)} shapes ({'quick' if a.quick else 'full'}); the grader uses "
|
| 115 |
+
f"DIFFERENT sizes in the same regime — optimize for generality\n")
|
| 116 |
+
vals, allok = [], True
|
| 117 |
+
for shp in shapes:
|
| 118 |
+
args = _mk(*shp, seed=sum(int(x) for x in shp) % 9973)
|
| 119 |
+
ref = _ref(*args)
|
| 120 |
+
try:
|
| 121 |
+
out = _agent(*args)
|
| 122 |
+
except Exception as ex:
|
| 123 |
+
print(f" {shp}: RAISED {type(ex).__name__}: {str(ex)[:70]}")
|
| 124 |
+
allok = False
|
| 125 |
+
continue
|
| 126 |
+
ok, val, msg = _check(out, ref)
|
| 127 |
+
allok = allok and ok
|
| 128 |
+
t = _bench(lambda: _agent(*args))
|
| 129 |
+
v = canonical_work(*shp) / t / 2**30 if t > 0 else 0.0
|
| 130 |
+
vals.append(v)
|
| 131 |
+
print(f" {str(shp):28s} {t*1e3:9.2f} ms | {v:9.2f} GB/s | {msg} {'ok' if ok else 'FAIL'}")
|
| 132 |
+
del args, ref, out
|
| 133 |
+
torch.cuda.empty_cache()
|
| 134 |
+
geo = math.exp(sum(math.log(max(v, 1e-9)) for v in vals) / len(vals)) if vals else 0.0
|
| 135 |
+
print(f"\n => GEOMEAN {geo:.2f} GB/s "
|
| 136 |
+
f"({'all correct' if allok else 'SOME WRONG — a wrong kernel scores 0, fix correctness first'})")
|
| 137 |
+
print(" This IS your score, and it is uncapped — higher is always better. Keep pushing.")
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
if __name__ == "__main__":
|
| 141 |
+
main()
|
tasks/video-sparse-attention/sparse-block-worklist-build/environment/reference.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Reference implementation — the CORRECTNESS SPEC for `build_block_worklist`.
|
| 2 |
+
|
| 3 |
+
This is correct but slow. It defines exactly what your kernel must reproduce; its speed has no
|
| 4 |
+
bearing on your score, which is an absolute GB/s number. GENERATED by _factory/build.py.
|
| 5 |
+
"""
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def build_block_worklist(bits, n_key_blocks, n_buckets):
|
| 10 |
+
"""Unpack, popcount, prefix-sum, compact and partition — written as dense boolean tensor algebra.
|
| 11 |
+
|
| 12 |
+
Correct and simple — it is the numerical SPECIFICATION, not a performance target. It materialises the
|
| 13 |
+
whole boolean mask one (batch, head) at a time and calls nonzero() on it.
|
| 14 |
+
"""
|
| 15 |
+
B, NH, NQ, NW = bits.shape
|
| 16 |
+
NK = n_key_blocks
|
| 17 |
+
dev = bits.device
|
| 18 |
+
sh = torch.arange(8, device=dev, dtype=torch.uint8)
|
| 19 |
+
|
| 20 |
+
counts = torch.empty(B, NH, NQ, device=dev, dtype=torch.int32)
|
| 21 |
+
chunks = []
|
| 22 |
+
for b in range(B):
|
| 23 |
+
for h in range(NH):
|
| 24 |
+
m = (((bits[b, h].unsqueeze(-1) >> sh) & 1) != 0).reshape(NQ, NW * 8)[:, :NK]
|
| 25 |
+
counts[b, h] = m.sum(-1, dtype=torch.int32)
|
| 26 |
+
nz = m.nonzero() # row-major: row asc, then col asc
|
| 27 |
+
base = (b * NH + h) * NQ
|
| 28 |
+
chunks.append(torch.stack([nz[:, 0].to(torch.int32) + base,
|
| 29 |
+
nz[:, 1].to(torch.int32)], dim=1))
|
| 30 |
+
pairs = torch.cat(chunks, dim=0)
|
| 31 |
+
|
| 32 |
+
flat = counts.reshape(-1)
|
| 33 |
+
offsets = torch.zeros(flat.numel() + 1, device=dev, dtype=torch.int32)
|
| 34 |
+
offsets[1:] = torch.cumsum(flat, 0, dtype=torch.int64).to(torch.int32)
|
| 35 |
+
L = int(offsets[-1].item())
|
| 36 |
+
|
| 37 |
+
split = (torch.arange(n_buckets + 1, device=dev, dtype=torch.int64) * L) // n_buckets
|
| 38 |
+
bucket_row = torch.searchsorted(offsets.to(torch.int64), split, right=False).to(torch.int32)
|
| 39 |
+
return counts, offsets, pairs, bucket_row
|
tasks/video-sparse-attention/sparse-block-worklist-build/environment/restrict-network.sh
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Outbound firewall (anti-cheat): allow ONLY DNS, loopback, docker-internal networks, and the LLM API
|
| 3 |
+
# endpoints the agent needs. Everything else is dropped — in particular pypi, github, and huggingface,
|
| 4 |
+
# so the agent cannot `pip install vllm` / `pip install sglang` / clone the reference moe_align kernel and
|
| 5 |
+
# copy it. torch + triton are already in the image, and mini-swe-agent is pre-installed (harbor's patched
|
| 6 |
+
# installer skips the network install when it is already present), so no package index is needed at run time.
|
| 7 |
+
#
|
| 8 |
+
# Runs as the container ENTRYPOINT before the CMD. iptables rules are network-namespace-wide, so they also
|
| 9 |
+
# apply to the agent's `docker exec` commands. Requires cap_add: NET_ADMIN.
|
| 10 |
+
set -uo pipefail
|
| 11 |
+
|
| 12 |
+
# LLM API endpoints the agent may reach. Extend at launch via ALLOWED_HOSTS=host1,host2 (no scheme).
|
| 13 |
+
API_HOSTS=(
|
| 14 |
+
api.fireworks.ai
|
| 15 |
+
openrouter.ai openrouter.io
|
| 16 |
+
api.openai.com api.anthropic.com generativelanguage.googleapis.com
|
| 17 |
+
api.together.xyz integrate.api.nvidia.com api.moonshot.cn api.kimi.com
|
| 18 |
+
)
|
| 19 |
+
# Auto-allow hosts from any *_BASE_URL / *_ENDPOINT env var (ANTHROPIC_BASE_URL, OPENAI_BASE_URL, …).
|
| 20 |
+
CUSTOM=()
|
| 21 |
+
while IFS='=' read -r n v; do
|
| 22 |
+
case "$n" in
|
| 23 |
+
*_BASE_URL|*_URL|*_ENDPOINT)
|
| 24 |
+
[ -n "$v" ] && CUSTOM+=("$(echo "$v" | sed 's|.*://||; s|[:/].*||')") ;;
|
| 25 |
+
esac
|
| 26 |
+
done < <(env)
|
| 27 |
+
if [ -n "${ALLOWED_HOSTS:-}" ]; then IFS=',' read -ra E <<< "$ALLOWED_HOSTS"; CUSTOM+=("${E[@]}"); fi
|
| 28 |
+
ALL_HOSTS=("${API_HOSTS[@]}" ${CUSTOM[@]+"${CUSTOM[@]}"})
|
| 29 |
+
|
| 30 |
+
if iptables -L OUTPUT -n >/dev/null 2>&1; then
|
| 31 |
+
echo "restrict-network: applying outbound allowlist firewall..."
|
| 32 |
+
iptables -F OUTPUT 2>/dev/null || true
|
| 33 |
+
iptables -A OUTPUT -o lo -j ACCEPT
|
| 34 |
+
iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
|
| 35 |
+
iptables -A OUTPUT -p udp --dport 53 -j ACCEPT
|
| 36 |
+
iptables -A OUTPUT -p tcp --dport 53 -j ACCEPT
|
| 37 |
+
iptables -A OUTPUT -d 10.0.0.0/8 -j ACCEPT
|
| 38 |
+
iptables -A OUTPUT -d 172.16.0.0/12 -j ACCEPT
|
| 39 |
+
iptables -A OUTPUT -d 192.168.0.0/16 -j ACCEPT
|
| 40 |
+
iptables -A OUTPUT -d 127.0.0.11 -j ACCEPT
|
| 41 |
+
for h in "${ALL_HOSTS[@]}"; do
|
| 42 |
+
for ip in $(getent ahosts "$h" 2>/dev/null | awk '{print $1}' | sort -u); do
|
| 43 |
+
iptables -A OUTPUT -d "$ip" -j ACCEPT
|
| 44 |
+
done
|
| 45 |
+
done
|
| 46 |
+
iptables -A OUTPUT -j REJECT --reject-with icmp-admin-prohibited
|
| 47 |
+
echo "restrict-network: outbound locked to DNS + LLM endpoints; pypi/github/HF blocked."
|
| 48 |
+
else
|
| 49 |
+
echo "restrict-network: WARNING — iptables unavailable (need cap_add NET_ADMIN); NOT firewalled." >&2
|
| 50 |
+
fi
|
| 51 |
+
|
| 52 |
+
exec "$@"
|
tasks/video-sparse-attention/sparse-block-worklist-build/environment/worklist.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Your implementation goes here.
|
| 2 |
+
|
| 3 |
+
Replace the body of `build_block_worklist` with a FAST implementation that reproduces the output of /app/reference.py
|
| 4 |
+
(same signature, same numerics within tolerance) but is much faster — see /app/instruction.md.
|
| 5 |
+
Run `python /app/measure.py` to check your correctness and achieved GB/s.
|
| 6 |
+
|
| 7 |
+
You may add helper modules, Triton kernels, CUDA extensions, caches, etc. — only this function's name,
|
| 8 |
+
signature and returned value are fixed by the contract.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def build_block_worklist(bits, n_key_blocks, n_buckets):
|
| 13 |
+
"""Bitmap -> CSR work list + a row-aligned equal-work partition.
|
| 14 |
+
|
| 15 |
+
Args:
|
| 16 |
+
bits: (B, NH, NQ, NK//8) uint8 — packed tile bitmap, LSB-first: bit (1 << t) of byte w of row
|
| 17 |
+
(b,h,i) means key tile 8*w + t is live for query tile i.
|
| 18 |
+
n_key_blocks: int — NK, the number of key tiles (a multiple of 8).
|
| 19 |
+
n_buckets: int — P, the number of equal-work buckets to cut the work list into.
|
| 20 |
+
|
| 21 |
+
Returns:
|
| 22 |
+
(counts, offsets, pairs, bucket_row):
|
| 23 |
+
counts: (B, NH, NQ) int32 — live key tiles per row (popcount).
|
| 24 |
+
offsets: (R+1,) int32 — exclusive prefix sum over the R = B*NH*NQ rows, offsets[R] = L.
|
| 25 |
+
pairs: (L, 2) int32 — [flat row id, key tile id] for every live pair, ROW-MAJOR order.
|
| 26 |
+
bucket_row: (P+1,) int32 — bucket p owns rows [bucket_row[p], bucket_row[p+1]).
|
| 27 |
+
All four are integer tensors and are compared EXACTLY.
|
| 28 |
+
"""
|
| 29 |
+
raise NotImplementedError("Implement a fast build_block_worklist in /app/worklist.py")
|
tasks/video-sparse-attention/sparse-block-worklist-build/instruction.md
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Write a fast block-sparse work-list builder (bitmap -> CSR + balanced partition)
|
| 2 |
+
|
| 3 |
+
You are given a **correct but slow** reference at **`/app/reference.py`** — `build_block_worklist(bits, n_key_blocks, n_buckets)`. **Read it, run it, profile it.**
|
| 4 |
+
|
| 5 |
+
Write **`/app/worklist.py`** with the **same signature** and the **same numerical output**, but **as fast as you can make it**.
|
| 6 |
+
|
| 7 |
+
```python
|
| 8 |
+
def build_block_worklist(bits, n_key_blocks, n_buckets):
|
| 9 |
+
...
|
| 10 |
+
```
|
| 11 |
+
|
| 12 |
+
## The computation (this is the exact spec)
|
| 13 |
+
|
| 14 |
+
`bits` is the packed output of an upstream mask builder: for the row `(b, h, i)`, key tile
|
| 15 |
+
`8*w + t` is live iff bit `1 << t` of byte `w` is set (**LSB first**). There are `NK` key tiles, `NK` a
|
| 16 |
+
multiple of 8, so a row is exactly `NK/8` bytes.
|
| 17 |
+
|
| 18 |
+
Rows are numbered **flat and row-major**: `row(b,h,i) = (b*NH + h)*NQ + i`, `R = B*NH*NQ` rows in total.
|
| 19 |
+
|
| 20 |
+
**1. Counts.** `counts[b,h,i]` = popcount of the row = number of live key tiles. Every row has at least one.
|
| 21 |
+
|
| 22 |
+
**2. Offsets.** The exclusive prefix sum of `counts` over the flat row order:
|
| 23 |
+
|
| 24 |
+
```
|
| 25 |
+
offsets[0] = 0
|
| 26 |
+
offsets[r+1] = offsets[r] + counts_flat[r]
|
| 27 |
+
offsets[R] = L # total live pairs
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
**3. Pairs.** The compacted work list, `L` entries of `[flat row id, key tile id]`, in **row-major order** —
|
| 31 |
+
rows in increasing flat order, and within a row the key tiles in increasing order. Row `r` therefore owns
|
| 32 |
+
exactly `pairs[offsets[r] : offsets[r+1]]`, and `pairs[j,0] == r` for every one of those `j`.
|
| 33 |
+
|
| 34 |
+
**4. Buckets.** A persistent grid of `P` CTAs wants equal work, but a CTA must not be handed half a row (it
|
| 35 |
+
would have to re-read that row's query tile). So the split points are snapped to row boundaries:
|
| 36 |
+
|
| 37 |
+
```
|
| 38 |
+
split[p] = (p * L) // P # integer division, p = 0 .. P
|
| 39 |
+
bucket_row[p] = the smallest r in [0, R] with offsets[r] >= split[p]
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
i.e. `bucket_row = searchsorted(offsets, split, side='left')`. Bucket `p` then owns rows
|
| 43 |
+
`[bucket_row[p], bucket_row[p+1])`, some of which are empty when `P` is large — that is expected and must be
|
| 44 |
+
reproduced exactly. `bucket_row[0]` is `0` and `bucket_row[P]` is `R`.
|
| 45 |
+
|
| 46 |
+
`/app/reference.py` unpacks the whole boolean mask per `(b, h)` and calls `nonzero()`. That is the exact
|
| 47 |
+
specification; it is deliberately simple rather than fast.
|
| 48 |
+
|
| 49 |
+
## The contract (fixed — do not change these)
|
| 50 |
+
|
| 51 |
+
| arg | shape | dtype | meaning |
|
| 52 |
+
|-----|-------|-------|---------|
|
| 53 |
+
| `bits` | `(B, NH, NQ, NK//8)` | `uint8` | packed tile bitmap, LSB-first |
|
| 54 |
+
| `n_key_blocks` | int | `NK`, a multiple of 8 (**not** always a multiple of 32) |
|
| 55 |
+
| `n_buckets` | int | `P`, the number of equal-work buckets |
|
| 56 |
+
|
| 57 |
+
**Return** a 4-tuple `(counts, offsets, pairs, bucket_row)` **in that order**:
|
| 58 |
+
|
| 59 |
+
| out | shape | dtype |
|
| 60 |
+
|-----|-------|-------|
|
| 61 |
+
| `counts` | `(B, NH, NQ)` | `int32` |
|
| 62 |
+
| `offsets` | `(R+1,)` where `R = B*NH*NQ` | `int32` |
|
| 63 |
+
| `pairs` | `(L, 2)` | `int32` |
|
| 64 |
+
| `bucket_row` | `(P+1,)` | `int32` |
|
| 65 |
+
|
| 66 |
+
**Every output is compared element-exactly** — this is index metadata, not arithmetic. `L` fits in `int32`
|
| 67 |
+
at every graded shape. `NQ` and `NK` need not be equal and need not be powers of two; `P` may be larger or
|
| 68 |
+
smaller than `R`. `bits` is read-only, CUDA and contiguous.
|
| 69 |
+
|
| 70 |
+
The shape of `pairs` is itself part of the answer: producing the right pairs in the wrong order, or the right
|
| 71 |
+
count in the wrong place, fails.
|
| 72 |
+
|
| 73 |
+
**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `NQ`, `NK`
|
| 74 |
+
3200-5120 tile ids (a 118k-token latent cut into ~30-token tiles), `NH` 24-40 heads, `B` 1-4, density 12-16%,
|
| 75 |
+
`P` 1024-4096 buckets. That is **150-300k rows and 100-200 million live pairs**, i.e. a 1.2-1.6 GiB pair list
|
| 76 |
+
written from a 150-250 MiB bitmap.
|
| 77 |
+
|
| 78 |
+
The output is 8x the input, so this is a **write-bound** kernel: the pair list is the whole cost, and the scan
|
| 79 |
+
that tells you where to put it is the whole difficulty.
|
| 80 |
+
|
| 81 |
+
## How success is decided (runs on GPU)
|
| 82 |
+
|
| 83 |
+
**1. Correctness — a required gate.** All four outputs are compared **element-exactly** at every graded shape, including the
|
| 84 |
+
timed ones. There is no tolerance: a single misplaced pair, a shifted offset or an off-by-one bucket boundary
|
| 85 |
+
scores **0**. Every output is an `int32` tensor, so the grader takes its exact-comparison path and the
|
| 86 |
+
numeric `tol` is never consulted at all — it is set to `0` to say so.
|
| 87 |
+
|
| 88 |
+
That was checked from both sides. **Achievable:** an independent implementation that shares no mechanism with
|
| 89 |
+
the reference — fully vectorised with no `(b, h)` python loop, the pair list built from a sorted flat index
|
| 90 |
+
instead of `nonzero()` per head, an `int64` `cumsum` for the scan — reproduces all four outputs
|
| 91 |
+
**element-for-element** at every `correct_shape`. **Discriminating:** partitioning the buckets by equal
|
| 92 |
+
*rows* instead of equal *work* leaves `counts`, `offsets` and `pairs` perfect and still mismatches **43
|
| 93 |
+
`bucket_row` entries**; MSB-first bit order inside each byte mismatches **47288 `pairs` entries**; and
|
| 94 |
+
emitting each row's columns in descending order mismatches **56000**. There is no numerical window here at
|
| 95 |
+
all — the gate is a pure equality check, which is the correct design for an all-integer output. A wrong kernel scores **0**, no matter how fast.
|
| 96 |
+
|
| 97 |
+
**2. Performance — this is your score, and it is an UNCAPPED leaderboard.**
|
| 98 |
+
|
| 99 |
+
```
|
| 100 |
+
reward = geomean over graded shapes of ( canonical_work(shape) / your_runtime ) [GB/s]
|
| 101 |
+
reward = 0 if the submission is wrong at any graded shape
|
| 102 |
+
```
|
| 103 |
+
|
| 104 |
+
`canonical_work` depends **only on the shape**, never on how you implemented it, so every submission is
|
| 105 |
+
credited the same work and this is a pure speed ranking in useful units:
|
| 106 |
+
|
| 107 |
+
```
|
| 108 |
+
R = B*NH*NQ; L = total live pairs (fixed by the shape)
|
| 109 |
+
BYTES = R*(NK/8) + 8*L + 8*R + 4*(P+1) # bitmap in, pair list + counts + offsets out
|
| 110 |
+
```
|
| 111 |
+
|
| 112 |
+
**There is no cap and no target.** Higher GB/s is always a strictly better score, so **push the
|
| 113 |
+
performance as hard as you can**. Getting a correct implementation is the *start* of the task, not the end of
|
| 114 |
+
it. Once correct, spend the entire remainder of your budget profiling and optimising, re-checking correctness
|
| 115 |
+
after every change. **Use your full time budget.**
|
| 116 |
+
|
| 117 |
+
Run **`python /app/measure.py`** at any point to see your per-shape and geomean GB/s plus correctness.
|
| 118 |
+
|
| 119 |
+
## Where the performance comes from
|
| 120 |
+
|
| 121 |
+
**Two passes, not three.** Pass 1: read the bitmap, `__popc` each row's words, write `counts`
|
| 122 |
+
and run a device-wide exclusive scan into `offsets`. Pass 2: re-read the bitmap and write each row's live
|
| 123 |
+
column ids straight to `pairs[offsets[r] ...]`. The bitmap is small (150-250 MiB) so reading it twice is
|
| 124 |
+
cheap; what you must not do is stage the pairs anywhere before their final position.
|
| 125 |
+
|
| 126 |
+
**The scan is over 150-300k elements** — a single-pass decoupled-lookback scan, or two small kernels
|
| 127 |
+
(block sums, then scan-of-scans, then add). Do not call a generic sort or `nonzero`.
|
| 128 |
+
|
| 129 |
+
**Compaction inside a row is a ballot.** With one warp per row, each lane holds one 32-bit word of the
|
| 130 |
+
bitmap; `__popc` of the lanes below it (a warp prefix sum) gives its base offset, and `__ffs` in a loop
|
| 131 |
+
emits the set bits in ascending order. No atomics, no shared-memory staging, and the writes are contiguous
|
| 132 |
+
per row.
|
| 133 |
+
|
| 134 |
+
**Write `pairs` as 64-bit stores.** Each entry is two `int32`; storing them as one `int2`/`uint64` per pair
|
| 135 |
+
halves the instruction count and keeps the stores perfectly coalesced within a row.
|
| 136 |
+
|
| 137 |
+
**`bucket_row` is `P+1` binary searches** over a monotone `int32` array — a single tiny kernel with one
|
| 138 |
+
thread per bucket, or a merge-path-style co-rank. It is nothing next to the pair writes, but it does depend
|
| 139 |
+
on `L`, so it has to come after the scan.
|
| 140 |
+
|
| 141 |
+
**Rows are ragged by +-1 around `DEN%` of `NK`,** so a row-per-warp mapping is naturally balanced; the reason
|
| 142 |
+
`bucket_row` exists at all is the *consumer* kernel, not this one.
|
| 143 |
+
|
| 144 |
+
## Precision and faithfulness (read this)
|
| 145 |
+
|
| 146 |
+
There is no floating-point arithmetic in this kernel at all: every input and output is an
|
| 147 |
+
integer, and every output is compared **exactly**. `tol` is `0` and the grader never reaches its
|
| 148 |
+
floating-point branch — this is the genuinely bit-exact case, confirmed by measuring an independent
|
| 149 |
+
vectorised implementation at element-for-element equality on every correctness shape.
|
| 150 |
+
|
| 151 |
+
Two things still count as precision:
|
| 152 |
+
|
| 153 |
+
**The prefix sum must not overflow.** `L` is up to ~2x10^8, which fits in `int32`, but an intermediate that
|
| 154 |
+
sums `counts` in 16-bit or that accumulates per-block sums in a narrower type will silently wrap. Accumulate
|
| 155 |
+
the scan in 32-bit (or 64-bit) and store `int32`.
|
| 156 |
+
|
| 157 |
+
**Bit order is LSB-first.** Bit `1 << t` of byte `w` is key tile `8*w + t`; reading the bytes as little-endian
|
| 158 |
+
32-bit words keeps that order (tile `32*W + 31` is the top bit of word `W`), which is why the warp ballot
|
| 159 |
+
trick works unchanged. Reversing it produces a valid-looking list with every row's columns permuted, which
|
| 160 |
+
fails immediately.
|
| 161 |
+
|
| 162 |
+
`n_key_blocks` is a multiple of 8 but not always of 32, so the last word of a row may be partial: mask the
|
| 163 |
+
bits above `NK` before the popcount, or you will emit tiles that do not exist.
|
| 164 |
+
|
| 165 |
+
### What the tolerance does NOT permit
|
| 166 |
+
|
| 167 |
+
The tolerance exists **only** to absorb low-precision arithmetic noise. You are responsible for a **faithful
|
| 168 |
+
implementation of the specified computation**. It is not a budget to spend on approximation. The following
|
| 169 |
+
are wrong answers even if they happen to land inside the tolerance at some shape:
|
| 170 |
+
|
| 171 |
+
- changing the algorithm to something that merely *approximates* the spec (dropping terms, truncating a
|
| 172 |
+
series, low-rank or sketched substitutes, skipping a correction term);
|
| 173 |
+
- shortening the computation (fewer iterations/steps than specified, early exit on a heuristic, subsampling
|
| 174 |
+
or striding over the sequence, ignoring positions whose contribution "looks small");
|
| 175 |
+
- computing at a coarser granularity than the spec (sharing a decay, scale, or normaliser across positions
|
| 176 |
+
that the spec gives their own);
|
| 177 |
+
- anything whose error **grows** with sequence length, batch, or head count.
|
| 178 |
+
|
| 179 |
+
A faithful bf16/fp8 kernel's error is *noise*: it stays flat as the problem grows and sits an order of
|
| 180 |
+
magnitude below the gate. An approximation's error is *bias*: it scales with the problem. The graded shapes
|
| 181 |
+
are deliberately large, so the difference shows up.
|
| 182 |
+
|
| 183 |
+
## What's available
|
| 184 |
+
|
| 185 |
+
- **Triton 3.6** (with Gluon), **CUDA C++ via `nvcc`** (`torch.utils.cpp_extension.load` for an inline
|
| 186 |
+
extension), header-only **CUTLASS** at `/opt/cutlass/include`, and the **CuTe DSL**
|
| 187 |
+
(`nvidia-cutlass-dsl`). C++ / CuTe DSL is the encouraged route; Triton is fully supported.
|
| 188 |
+
- `torch` 2.11 (CUDA 12.8) and `einops` for bookkeeping.
|
| 189 |
+
- A GPU with compute capability sm≥90 (Hopper or newer).
|
| 190 |
+
- **No internet access.** `pip install` and cloning repos are blocked. Everything you are permitted to use is
|
| 191 |
+
already installed, and no library implementation of this kernel exists on the machine.
|
| 192 |
+
- Manage any long-running background job (a build, an `ncu`/`nsys` profile) by its **recorded PID** — see
|
| 193 |
+
`/app/CLAUDE.md` and `/app/PROCESS_MANAGEMENT.md`.
|
| 194 |
+
|
| 195 |
+
## How the grading actually runs (so there are no surprises)
|
| 196 |
+
|
| 197 |
+
- **`/app/worklist.py` is the only file that is graded.** The grader imports `build_block_worklist` from it and reads nothing
|
| 198 |
+
else from `/app`.
|
| 199 |
+
- **The grader is not on this machine while you work.** It is copied in only after your session ends and it
|
| 200 |
+
carries its **own private copy of the reference** and its own input generator. Editing `/app/reference.py`
|
| 201 |
+
or `/app/measure.py` is allowed — they are yours to experiment with — but it has **no effect whatsoever on
|
| 202 |
+
your score**. Do not spend budget on them.
|
| 203 |
+
- **Every timed repetition uses freshly generated inputs**, and the output of a timed call is itself checked
|
| 204 |
+
against the reference. Caching or memoizing a result and replaying it fails the correctness gate rather
|
| 205 |
+
than producing a fast measurement. Ordinary shape-keyed JIT/autotune caching is fine and is not penalised.
|
| 206 |
+
- **The timed shapes are correctness-checked too.** Being correct only at the small shapes scores **0**.
|
| 207 |
+
- Inputs are random each grade and the graded shapes are not the ones in `measure.py`.
|
tasks/video-sparse-attention/sparse-block-worklist-build/task.toml
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
schema_version = "1.1"
|
| 2 |
+
|
| 3 |
+
[task]
|
| 4 |
+
name = "mle-bench/sparse-block-worklist-build"
|
| 5 |
+
description = "Between the mask builder and the attention kernel sits the piece nobody writes about and everybody needs: turning a per-head tile BITMAP into the flat work list a block-sparse attention kernel actually consumes. Popcount every row, prefix-sum 300k rows into CSR offsets, compact the live (query tile, key tile) pairs in row-major order, and cut the result into equal-work slices for a persistent grid. It is a scan and a stream compaction over a gigabyte of pairs, and it runs before every attention call."
|
| 6 |
+
authors = []
|
| 7 |
+
keywords = ["mle", "kernel-generation", "sparse-attention", "video-diffusion", "block-mask", "prefix-sum", "stream-compaction", "scheduling", "csr", "load-balancing"]
|
| 8 |
+
|
| 9 |
+
[metadata]
|
| 10 |
+
suite = "mle-bench"
|
| 11 |
+
group = "kernel-generation"
|
| 12 |
+
level = "1.0"
|
| 13 |
+
difficulty = "hard"
|
| 14 |
+
category = "mle"
|
| 15 |
+
tags = [ "mle", "kernel-generation", "kernels", "gpu", "real-world",]
|
| 16 |
+
|
| 17 |
+
[verifier]
|
| 18 |
+
timeout_sec = 1800.0
|
| 19 |
+
|
| 20 |
+
[agent]
|
| 21 |
+
timeout_sec = 14400.0
|
| 22 |
+
|
| 23 |
+
# GPU request: honored by Modal/GKE/Daytona. On the local docker backend set environment.override_gpus: 0
|
| 24 |
+
# in the job config and attach a GPU via configs/gpu_overlay_nvidia.yaml (see RUNNING.md §5).
|
| 25 |
+
[environment]
|
| 26 |
+
build_timeout_sec = 3600.0
|
| 27 |
+
cpus = 8
|
| 28 |
+
memory_mb = 65536
|
| 29 |
+
storage_mb = 40960
|
| 30 |
+
gpus = 1
|
| 31 |
+
network_mode = "public"
|
| 32 |
+
mcp_servers = []
|
| 33 |
+
|
| 34 |
+
[verifier.env]
|
| 35 |
+
|
| 36 |
+
[environment.env]
|
| 37 |
+
|
| 38 |
+
[solution.env]
|
tasks/video-sparse-attention/sparse-block-worklist-build/tests/test.sh
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# GENERATED by _factory/build.py. python3 (not python): some CUDA bases lack the symlink.
|
| 3 |
+
set -u
|
| 4 |
+
mkdir -p /logs/verifier
|
| 5 |
+
python3 /tests/verify_env.py
|
tasks/video-sparse-attention/sparse-block-worklist-build/tests/verify_env.py
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""sparse-block-worklist-build verifier — correctness gate + achieved-GB/s SPEED LEADERBOARD (uncapped).
|
| 2 |
+
|
| 3 |
+
reward = 0 if the submission is incorrect
|
| 4 |
+
reward = geomean over graded shapes of GB/s otherwise
|
| 5 |
+
|
| 6 |
+
GENERATED by _factory/build.py — do not edit here; edit the spec and regenerate.
|
| 7 |
+
|
| 8 |
+
There is no gold solution and no oracle: the score is an absolute hardware metric, so it is hardware-portable
|
| 9 |
+
by construction and nothing has to be vendored, sealed, or re-benchmarked.
|
| 10 |
+
|
| 11 |
+
CORRECTNESS is a hard gate, checked against an INDEPENDENT (embedded) copy of the reference at every graded
|
| 12 |
+
shape including the timed ones, so editing /app/reference.py cannot affect grading and a fast wrong kernel
|
| 13 |
+
scores 0.
|
| 14 |
+
|
| 15 |
+
ANTI-CHEAT on the timing path: every timed rep runs on FRESHLY generated inputs, and the output of the last
|
| 16 |
+
timed rep is itself validated against the reference for those exact inputs. A submission that memoizes a
|
| 17 |
+
result and replays it fails the gate instead of posting an inflated number. Warm-up runs on a separate
|
| 18 |
+
throwaway input set, so ordinary shape-keyed JIT/autotune caching is not penalised.
|
| 19 |
+
|
| 20 |
+
WORK is attributed by a CANONICAL formula that depends only on the shape, never on the implementation, so all
|
| 21 |
+
submissions are credited identically and the ranking is a pure speed ranking.
|
| 22 |
+
"""
|
| 23 |
+
import importlib.util
|
| 24 |
+
import json
|
| 25 |
+
import math
|
| 26 |
+
import os
|
| 27 |
+
import sys
|
| 28 |
+
import traceback
|
| 29 |
+
|
| 30 |
+
import torch
|
| 31 |
+
|
| 32 |
+
REWARD_DIR = "/logs/verifier"
|
| 33 |
+
MODULE_PATH = "/app/worklist.py"
|
| 34 |
+
TOL = 0.0
|
| 35 |
+
NAMES = ('counts', 'offsets', 'pairs', 'bucket_row')
|
| 36 |
+
|
| 37 |
+
GRADER_SHAPES = [(2, 40, 4096, 4096, 12, 2048), (2, 24, 4608, 4608, 14, 1024), (4, 24, 3200, 3200, 16, 4096), (1, 40, 5120, 5120, 14, 2048), (2, 32, 3840, 3840, 16, 1536)]
|
| 38 |
+
CORRECT_SHAPES = [(1, 4, 128, 128, 12, 32), (2, 3, 96, 256, 15, 17), (1, 6, 200, 64, 25, 8), (1, 2, 64, 512, 9, 64), (2, 5, 150, 128, 30, 100), (1, 3, 77, 88, 18, 13)]
|
| 39 |
+
|
| 40 |
+
sys.path.insert(0, "/app")
|
| 41 |
+
|
| 42 |
+
def _live_counts(B, NH, NQ, NK, DEN):
|
| 43 |
+
"""Live key tiles per (batch, head, query tile), from the SHAPE ALONE.
|
| 44 |
+
|
| 45 |
+
About DEN percent of the NK tiles survive, jittered by +-1 per row so the rows are genuinely ragged, and
|
| 46 |
+
always at least 1.
|
| 47 |
+
"""
|
| 48 |
+
out = []
|
| 49 |
+
base = (NK * DEN) // 100
|
| 50 |
+
for b in range(B):
|
| 51 |
+
for h in range(NH):
|
| 52 |
+
for i in range(NQ):
|
| 53 |
+
c = base + ((b * 31 + h * 17 + i * 7) % 3) - 1
|
| 54 |
+
out.append(min(max(c, 1), NK))
|
| 55 |
+
return out
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def canonical_work(B, NH, NQ, NK, DEN, P):
|
| 59 |
+
"""BYTES moved by one call, from the SHAPE ALONE.
|
| 60 |
+
|
| 61 |
+
Read the packed bitmap once (NK/8 bytes per row), write the counts and the CSR offsets (4 bytes per
|
| 62 |
+
row each), and write the compacted pair list (8 bytes per live pair). The live count is fixed by the
|
| 63 |
+
shape, so the pair list has the same length for every submission.
|
| 64 |
+
"""
|
| 65 |
+
R = B * NH * NQ
|
| 66 |
+
L = sum(_live_counts(B, NH, NQ, NK, DEN))
|
| 67 |
+
return R * (NK // 8) + 8 * L + 8 * R + 4 * (P + 1)
|
| 68 |
+
|
| 69 |
+
def _ref(bits, n_key_blocks, n_buckets):
|
| 70 |
+
"""Unpack, popcount, prefix-sum, compact and partition — written as dense boolean tensor algebra.
|
| 71 |
+
|
| 72 |
+
Correct and simple — it is the numerical SPECIFICATION, not a performance target. It materialises the
|
| 73 |
+
whole boolean mask one (batch, head) at a time and calls nonzero() on it.
|
| 74 |
+
"""
|
| 75 |
+
B, NH, NQ, NW = bits.shape
|
| 76 |
+
NK = n_key_blocks
|
| 77 |
+
dev = bits.device
|
| 78 |
+
sh = torch.arange(8, device=dev, dtype=torch.uint8)
|
| 79 |
+
|
| 80 |
+
counts = torch.empty(B, NH, NQ, device=dev, dtype=torch.int32)
|
| 81 |
+
chunks = []
|
| 82 |
+
for b in range(B):
|
| 83 |
+
for h in range(NH):
|
| 84 |
+
m = (((bits[b, h].unsqueeze(-1) >> sh) & 1) != 0).reshape(NQ, NW * 8)[:, :NK]
|
| 85 |
+
counts[b, h] = m.sum(-1, dtype=torch.int32)
|
| 86 |
+
nz = m.nonzero() # row-major: row asc, then col asc
|
| 87 |
+
base = (b * NH + h) * NQ
|
| 88 |
+
chunks.append(torch.stack([nz[:, 0].to(torch.int32) + base,
|
| 89 |
+
nz[:, 1].to(torch.int32)], dim=1))
|
| 90 |
+
pairs = torch.cat(chunks, dim=0)
|
| 91 |
+
|
| 92 |
+
flat = counts.reshape(-1)
|
| 93 |
+
offsets = torch.zeros(flat.numel() + 1, device=dev, dtype=torch.int32)
|
| 94 |
+
offsets[1:] = torch.cumsum(flat, 0, dtype=torch.int64).to(torch.int32)
|
| 95 |
+
L = int(offsets[-1].item())
|
| 96 |
+
|
| 97 |
+
split = (torch.arange(n_buckets + 1, device=dev, dtype=torch.int64) * L) // n_buckets
|
| 98 |
+
bucket_row = torch.searchsorted(offsets.to(torch.int64), split, right=False).to(torch.int32)
|
| 99 |
+
return counts, offsets, pairs, bucket_row
|
| 100 |
+
|
| 101 |
+
def _mk(B, NH, NQ, NK, DEN, P, seed):
|
| 102 |
+
gen = torch.Generator(device="cuda").manual_seed(seed)
|
| 103 |
+
cnt = torch.tensor(_live_counts(B, NH, NQ, NK, DEN), device="cuda").view(B, NH, NQ)
|
| 104 |
+
kmax = int(cnt.max().item())
|
| 105 |
+
sh = torch.arange(8, device="cuda", dtype=torch.int32)
|
| 106 |
+
bits = torch.empty(B, NH, NQ, NK // 8, device="cuda", dtype=torch.uint8)
|
| 107 |
+
for b in range(B):
|
| 108 |
+
for h in range(NH):
|
| 109 |
+
r = torch.rand(NQ, NK, device="cuda", generator=gen)
|
| 110 |
+
idx = r.topk(kmax, dim=-1).indices # (NQ, kmax) random distinct columns
|
| 111 |
+
live = torch.arange(kmax, device="cuda").view(1, -1) < cnt[b, h].view(-1, 1)
|
| 112 |
+
m = torch.zeros(NQ, NK, dtype=torch.bool, device="cuda")
|
| 113 |
+
m.scatter_(1, torch.where(live, idx, idx[:, :1]), True) # rank 0 is always live
|
| 114 |
+
bits[b, h] = ((m.view(NQ, NK // 8, 8).to(torch.int32) << sh).sum(-1)).to(torch.uint8)
|
| 115 |
+
return bits, NK, P
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def _check(out, ref):
|
| 119 |
+
"""-> (ok, value, msg). value = MAX relative error across the returned tuple."""
|
| 120 |
+
if out is None or len(out) != len(NAMES):
|
| 121 |
+
return False, 1.0, f"expected a {len(NAMES)}-tuple {NAMES}"
|
| 122 |
+
per = []
|
| 123 |
+
for n, a, b in zip(NAMES, out, ref):
|
| 124 |
+
if a is None or tuple(a.shape) != tuple(b.shape):
|
| 125 |
+
return False, 1.0, f"{n} bad shape"
|
| 126 |
+
if b.dtype in (torch.int8, torch.int16, torch.int32, torch.int64, torch.uint8, torch.bool):
|
| 127 |
+
# exact: .float() is lossy above 2**24 and would let distinct large ids compare equal
|
| 128 |
+
bad = int((a != b).sum())
|
| 129 |
+
if bad:
|
| 130 |
+
return False, 1.0, f"{n}: {bad} elements differ"
|
| 131 |
+
continue
|
| 132 |
+
per.append((n, float((a.float() - b.float()).norm() / (b.float().norm() + 1e-12))))
|
| 133 |
+
if not per:
|
| 134 |
+
return True, 0.0, "all integer outputs exact"
|
| 135 |
+
wn, wv = max(per, key=lambda x: x[1])
|
| 136 |
+
return wv <= TOL, wv, f"worst {wn} {wv:.2e}"
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def _bench_fresh(fn, mkargs, reps=5, warm=3):
|
| 140 |
+
"""Time `fn` on FRESH inputs every rep -> (min_seconds, timed_ok). See the module docstring."""
|
| 141 |
+
wargs = mkargs(0)
|
| 142 |
+
for _ in range(warm):
|
| 143 |
+
fn(*wargs)
|
| 144 |
+
torch.cuda.synchronize()
|
| 145 |
+
del wargs
|
| 146 |
+
torch.cuda.empty_cache()
|
| 147 |
+
|
| 148 |
+
best, timed_ok = float("inf"), True
|
| 149 |
+
for i in range(reps):
|
| 150 |
+
args = mkargs(10_000 + i)
|
| 151 |
+
s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
|
| 152 |
+
s.record()
|
| 153 |
+
out = fn(*args)
|
| 154 |
+
e.record()
|
| 155 |
+
torch.cuda.synchronize()
|
| 156 |
+
best = min(best, s.elapsed_time(e))
|
| 157 |
+
if i == reps - 1:
|
| 158 |
+
timed_ok = _check(out, _ref(*args))[0]
|
| 159 |
+
del args, out
|
| 160 |
+
torch.cuda.empty_cache()
|
| 161 |
+
return best / 1e3, timed_ok
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def _geomean(xs):
|
| 165 |
+
return math.exp(sum(math.log(max(v, 1e-9)) for v in xs) / len(xs)) if xs else 0.0
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def main():
|
| 169 |
+
details, correct_gate, geo = {}, False, 0.0
|
| 170 |
+
try:
|
| 171 |
+
spec = importlib.util.spec_from_file_location("submission", MODULE_PATH)
|
| 172 |
+
m = importlib.util.module_from_spec(spec)
|
| 173 |
+
spec.loader.exec_module(m)
|
| 174 |
+
fn = m.build_block_worklist
|
| 175 |
+
|
| 176 |
+
corr_ok, msg = True, ""
|
| 177 |
+
for i, shp in enumerate(CORRECT_SHAPES):
|
| 178 |
+
args = _mk(*shp, seed=10 + i)
|
| 179 |
+
ok, val, m_ = _check(fn(*args), _ref(*args))
|
| 180 |
+
if not ok:
|
| 181 |
+
corr_ok, msg = False, f"cfg{i} {shp} {m_}"
|
| 182 |
+
break
|
| 183 |
+
del args
|
| 184 |
+
torch.cuda.empty_cache()
|
| 185 |
+
details["correct_msg"] = msg or "all correctness shapes pass"
|
| 186 |
+
|
| 187 |
+
vals, per_shape, perf_ok = [], [], corr_ok
|
| 188 |
+
for i, shp in enumerate(GRADER_SHAPES):
|
| 189 |
+
args = _mk(*shp, seed=100 + i)
|
| 190 |
+
ok, val, m_ = _check(fn(*args), _ref(*args))
|
| 191 |
+
if not ok:
|
| 192 |
+
perf_ok = False
|
| 193 |
+
del args
|
| 194 |
+
torch.cuda.empty_cache()
|
| 195 |
+
t, timed_ok = _bench_fresh(fn, lambda s, _p=shp: _mk(*_p, seed=s))
|
| 196 |
+
if not timed_ok:
|
| 197 |
+
perf_ok = False
|
| 198 |
+
v = canonical_work(*shp) / t / 2**30 if t > 0 else 0.0
|
| 199 |
+
vals.append(v)
|
| 200 |
+
per_shape.append({"shape": list(shp), "gbps": round(v, 3), "ms": round(t * 1e3, 3),
|
| 201 |
+
"check": m_, "timed_ok": timed_ok})
|
| 202 |
+
geo = _geomean(vals)
|
| 203 |
+
details.update(per_shape=per_shape, geomean=round(geo, 4), perf_size_ok=perf_ok)
|
| 204 |
+
correct_gate = corr_ok and perf_ok
|
| 205 |
+
except Exception as e:
|
| 206 |
+
details["error"] = f"{e.__class__.__name__}: {e}"[:220]
|
| 207 |
+
details["trace"] = traceback.format_exc()[-800:]
|
| 208 |
+
|
| 209 |
+
reward = round(geo, 4) if correct_gate else 0.0
|
| 210 |
+
os.makedirs(REWARD_DIR, exist_ok=True)
|
| 211 |
+
json.dump({"reward": reward, "correct": 1.0 if correct_gate else 0.0,
|
| 212 |
+
"geomean": round(geo, 4), "metric": "GB/s (geomean over graded shapes)"},
|
| 213 |
+
open(f"{REWARD_DIR}/reward.json", "w"), indent=2)
|
| 214 |
+
open(f"{REWARD_DIR}/reward.txt", "w").write(str(reward))
|
| 215 |
+
json.dump(details, open(f"{REWARD_DIR}/details.json", "w"), indent=2, default=str)
|
| 216 |
+
print("reward:", reward, "GB/s | correct:", 1.0 if correct_gate else 0.0)
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
main()
|
tasks/video-sparse-attention/spatial-window-temporal-global/RUN.md
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Running `spatial-window-temporal-global`
|
| 2 |
+
|
| 3 |
+
Local in space, global in time: every token attends densely inside a small window of its own frame, and additionally to a uniform stride-`s` sample of every OTHER frame, so the whole clip stays visible for a few percent of the keys. Two gathers with opposite characters — a short 2D box with row stride Ww, and a long stride-`s` comb spanning the entire sequence — sharing one softmax, plus a boundary rule that keeps the two sets disjoint.
|
| 4 |
+
|
| 5 |
+
| | |
|
| 6 |
+
|---|---|
|
| 7 |
+
| **Task id** | `mle-bench/spatial-window-temporal-global` |
|
| 8 |
+
| **Group** | `kernel-generation` |
|
| 9 |
+
| **GPUs** | 1 |
|
| 10 |
+
| **Agent edits** | `/app/win_global.py` |
|
| 11 |
+
| **Score** | achieved **TFLOP/s** (uncapped speed leaderboard), `0` if incorrect |
|
| 12 |
+
| **Grade output** | `tests/test.sh` -> `/logs/verifier/reward.json` |
|
| 13 |
+
|
| 14 |
+
## Run through harbor
|
| 15 |
+
|
| 16 |
+
```bash
|
| 17 |
+
harbor run --dataset-path kernel-generation/kernels/spatial-window-temporal-global --task-name spatial-window-temporal-global \
|
| 18 |
+
--agent claude-code --model anthropic/claude-opus-4-1 -e docker
|
| 19 |
+
```
|
| 20 |
+
|
| 21 |
+
## Run manually
|
| 22 |
+
|
| 23 |
+
```bash
|
| 24 |
+
cd kernel-generation/kernels/spatial-window-temporal-global
|
| 25 |
+
docker build -t spatial-window-temporal-global environment/
|
| 26 |
+
docker run -d --name v --gpus '"device=0"' --shm-size=8g --entrypoint sleep spatial-window-temporal-global infinity
|
| 27 |
+
docker cp tests v:/tests && docker exec v bash /tests/test.sh # untouched start -> reward 0.0
|
| 28 |
+
docker rm -f v
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
Use an **idle** GPU: the score is a timing measurement.
|
| 32 |
+
|
| 33 |
+
## Design
|
| 34 |
+
|
| 35 |
+
Correctness is a hard gate; the score is an absolute hardware metric (TFLOP/s), so the task is
|
| 36 |
+
hardware-portable and needs no gold solution, no oracle, and nothing vendored or sealed.
|
| 37 |
+
|
| 38 |
+
Anti-cheat is structural: the image holds only the permitted toolchain and has no internet; the grader is
|
| 39 |
+
copied in at grade time with its own private copy of the reference; and every timed rep runs on fresh inputs
|
| 40 |
+
with the timed output itself validated, so memoize-and-replay fails the gate.
|
| 41 |
+
|
| 42 |
+
Generated by `_factory/build.py` — edit the spec and regenerate rather than editing this task by hand.
|
tasks/video-sparse-attention/spatial-window-temporal-global/environment/CLAUDE.md
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Working in this environment
|
| 2 |
+
|
| 3 |
+
## ⚠️ Stop background processes without killing yourself
|
| 4 |
+
|
| 5 |
+
You are launched as `claude --print -- '<the task instruction>'`, so the task text — including the
|
| 6 |
+
file names and commands it mentions — is on **your own** process's command line. Any command that
|
| 7 |
+
finds processes by **matching that text** (`pkill -f …`, `pgrep -f … | xargs kill`, a `/proc`
|
| 8 |
+
cmdline scan, `fuser -k`, `killall`) can match and **kill the agent itself**, ending your run
|
| 9 |
+
(`NonZeroAgentExitCodeError`) and grading you on unfinished work.
|
| 10 |
+
|
| 11 |
+
This bites whenever you background something and later stop/restart it — a **server**, a long
|
| 12 |
+
**build** or **training run**, or an **ncu / nsys profiling** session.
|
| 13 |
+
|
| 14 |
+
**Always** manage a background process by its **exact recorded PID**, never by a name pattern:
|
| 15 |
+
|
| 16 |
+
```bash
|
| 17 |
+
nohup <your command> > /tmp/job.log 2>&1 & echo $! > /tmp/job.pid # start + record the PID
|
| 18 |
+
kill "$(cat /tmp/job.pid)"; sleep 3 # stop (SIGTERM); -9 only if needed
|
| 19 |
+
```
|
| 20 |
+
|
| 21 |
+
Use `setsid` and kill the process **group** (`kill -- -"$(cat /tmp/job.pid)"`) if it spawns children.
|
| 22 |
+
If you must enumerate processes, match a **unique token that is NOT anywhere in this prompt** and
|
| 23 |
+
**exclude any cmdline containing `claude` or `--print`** — `pgrep -af`, and look before you kill.
|
| 24 |
+
|
| 25 |
+
Full details + safe recipes: **`/app/PROCESS_MANAGEMENT.md`**.
|
tasks/video-sparse-attention/spatial-window-temporal-global/environment/Dockerfile
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Kernel-generation task: Write a fast spatial-window + strided-global video attention kernel
|
| 2 |
+
#
|
| 3 |
+
# Local in space, global in time: every token attends densely inside a small window of its own frame, and additionally to a uniform stride-`s` sample of every OTHER frame, so the whole clip stays visible for a few percent of the keys. Two gathers with opposite characters — a short 2D box with row stride Ww, and a long stride-`s` comb spanning the entire sequence — sharing one softmax, plus a boundary rule that keeps the two sets disjoint.
|
| 4 |
+
#
|
| 5 |
+
# SCORING: correctness is a hard gate; the score is achieved TFLOP/s (uncapped leaderboard, 0 if wrong).
|
| 6 |
+
# There is no gold solution and no oracle, so nothing has to be vendored or sealed.
|
| 7 |
+
#
|
| 8 |
+
# TOOLCHAIN POLICY: the agent writes the kernel with Triton (+Gluon), CUDA C++ via nvcc, CUTLASS headers, or
|
| 9 |
+
# the CuTe DSL. Enforcement is by ABSENCE, not by scanning: only the permitted toolchain is installed and
|
| 10 |
+
# there is no internet, so nothing else can be obtained.
|
| 11 |
+
#
|
| 12 |
+
# GENERATED by _factory/build.py.
|
| 13 |
+
FROM pytorch/pytorch:2.11.0-cuda12.8-cudnn9-devel
|
| 14 |
+
|
| 15 |
+
# NOTE: every heavy layer comes FIRST and depends only on {base_image, pip_extra}, so all tasks in this
|
| 16 |
+
# lane share the same cached layers. The task-specific COPYs are LAST. Do not reorder.
|
| 17 |
+
RUN pip install --break-system-packages --no-cache-dir einops nvidia-cutlass-dsl && \
|
| 18 |
+
apt-get update && apt-get install -y --no-install-recommends iptables iproute2 curl ca-certificates build-essential git && \
|
| 19 |
+
curl -LsSf https://astral.sh/uv/install.sh | sh && \
|
| 20 |
+
/root/.local/bin/uv tool install mini-swe-agent
|
| 21 |
+
# header-only CUTLASS for the agent's CUDA/CuTe route
|
| 22 |
+
RUN git clone --depth 1 https://github.com/NVIDIA/cutlass /opt/cutlass && rm -rf /opt/cutlass/.git
|
| 23 |
+
# pre-bake Claude Code; harbor's claude_code.install() skips when present
|
| 24 |
+
RUN curl -fsSL https://deb.nodesource.com/setup_22.x | bash - && \
|
| 25 |
+
apt-get install -y nodejs procps && \
|
| 26 |
+
npm install -g @anthropic-ai/claude-code && claude --version
|
| 27 |
+
ENV PATH=/root/.local/bin:$PATH
|
| 28 |
+
ENV DISABLE_TELEMETRY=1 DISABLE_AUTOUPDATER=1 DISABLE_ERROR_REPORTING=1 CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1
|
| 29 |
+
|
| 30 |
+
COPY restrict-network.sh /app/restrict-network.sh
|
| 31 |
+
RUN chmod +x /app/restrict-network.sh
|
| 32 |
+
# strip apt sources LAST so harbor's post-firewall apt step is a no-op that succeeds
|
| 33 |
+
RUN rm -rf /var/lib/apt/lists/* /etc/apt/sources.list /etc/apt/sources.list.d
|
| 34 |
+
|
| 35 |
+
WORKDIR /app
|
| 36 |
+
COPY CLAUDE.md PROCESS_MANAGEMENT.md /app/
|
| 37 |
+
|
| 38 |
+
# task-specific files LAST so the layers above stay shared across every task
|
| 39 |
+
COPY reference.py /app/reference.py
|
| 40 |
+
COPY measure.py /app/measure.py
|
| 41 |
+
COPY win_global.py /app/win_global.py
|
tasks/video-sparse-attention/spatial-window-temporal-global/environment/PROCESS_MANAGEMENT.md
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Managing background processes — READ THIS before you `kill` anything
|
| 2 |
+
|
| 3 |
+
You may start and stop background processes while iterating — a **server**, a long **build** or
|
| 4 |
+
**training run**, or an **ncu / nsys profiling** session. **The way you stop one can silently kill
|
| 5 |
+
*your own agent process* and end the whole run.** This has happened repeatedly, including via a
|
| 6 |
+
hand-rolled `/proc` scan — not just `pkill`. Read this once and follow the safe recipe.
|
| 7 |
+
|
| 8 |
+
## The trap: matching task text against process command lines
|
| 9 |
+
|
| 10 |
+
You were launched as roughly:
|
| 11 |
+
|
| 12 |
+
```
|
| 13 |
+
claude --print -- '<the entire task instruction text>'
|
| 14 |
+
```
|
| 15 |
+
|
| 16 |
+
The full task instruction is on **your own** process's command line, and it contains the file names
|
| 17 |
+
and commands the task mentions (e.g. `server.py`, `build.sh`, `train.py`, `solution.cu`, `/app/...`).
|
| 18 |
+
So **any** command that finds processes by matching those strings will match — and can kill — **the
|
| 19 |
+
agent itself**:
|
| 20 |
+
|
| 21 |
+
```
|
| 22 |
+
pkill -9 -f "train.py" # matches the claude agent -> kills YOU
|
| 23 |
+
pgrep -f "server.py" | xargs kill # same: the pid list includes claude
|
| 24 |
+
for p in $(pgrep -f build.sh); do kill -9 $p; done # same
|
| 25 |
+
for pid in /proc/*; do case "$(cmdline)" in *solution*) kill -9 $pid;; esac; done # same
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
It is **not about `pkill`** — it is about **matching a string that appears in your prompt**. `pgrep`,
|
| 29 |
+
a `/proc` scan, `fuser`, or `nvidia-smi`-pid loops all have the same failure if the match pattern (or
|
| 30 |
+
the surviving pid list) includes the `claude` process. When you `kill -9` yourself the run dies
|
| 31 |
+
immediately (`NonZeroAgentExitCodeError`) and you are graded on whatever was already in place — usually
|
| 32 |
+
worse than what you were about to finish.
|
| 33 |
+
|
| 34 |
+
## The one safe rule: kill only the exact PID you recorded
|
| 35 |
+
|
| 36 |
+
**Start** a background job and record its PID in a file:
|
| 37 |
+
|
| 38 |
+
```bash
|
| 39 |
+
nohup <your command> > /tmp/job.log 2>&1 &
|
| 40 |
+
echo $! > /tmp/job.pid
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
**Stop / restart** by that exact PID — never by a name pattern:
|
| 44 |
+
|
| 45 |
+
```bash
|
| 46 |
+
kill "$(cat /tmp/job.pid)" 2>/dev/null # SIGTERM: lets it release the GPU / flush cleanly
|
| 47 |
+
sleep 3
|
| 48 |
+
kill -9 "$(cat /tmp/job.pid)" 2>/dev/null # force only if it did not exit
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
If the job spawns workers, run it in its own process group and signal the group by its (negative)
|
| 52 |
+
PGID — still an exact id, never a pattern:
|
| 53 |
+
|
| 54 |
+
```bash
|
| 55 |
+
setsid <your command> > /tmp/job.log 2>&1 < /dev/null & echo $! > /tmp/job.pid
|
| 56 |
+
kill -TERM -- "-$(cat /tmp/job.pid)" 2>/dev/null
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
## If you ever enumerate processes, EXCLUDE the agent
|
| 60 |
+
|
| 61 |
+
Prefer not to. But if you must scan (e.g. hunting a leaked worker), **exclude the `claude` agent and
|
| 62 |
+
your own shell**, and match on a **unique token that is NOT anywhere in this prompt** — give your job
|
| 63 |
+
a unique name and match only that:
|
| 64 |
+
|
| 65 |
+
```bash
|
| 66 |
+
# job named e.g. job_7x3q9 — a token that appears NOWHERE in the task text
|
| 67 |
+
pgrep -af job_7x3q9 | grep -v -E 'claude|--print|pgrep|grep|bash' # LOOK FIRST
|
| 68 |
+
# only kill pids from THIS filtered list, and never a pid whose cmdline contains 'claude' or '--print'
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
Do **not** add a prompt word (a file name, `/app`, `python3`, …) to the pattern "just in case" — that
|
| 72 |
+
single addition re-introduces the self-kill. Match the unique token **only**.
|
| 73 |
+
|
| 74 |
+
## Freeing the GPU without going nuclear
|
| 75 |
+
|
| 76 |
+
If VRAM stays high after you stop a GPU job, the usual cause is a **child process** or a not-yet-
|
| 77 |
+
collected CUDA context — not a stray process you need to hunt across `/proc`. Do this instead of a
|
| 78 |
+
`/proc` sweep:
|
| 79 |
+
|
| 80 |
+
- Kill the job **by its recorded PID / PGID** (above) and `sleep 5–10`; the CUDA context frees after
|
| 81 |
+
the process fully exits.
|
| 82 |
+
- Make the job release cleanly on `SIGTERM` (drop the model / `torch.cuda.empty_cache()` / exit) so a
|
| 83 |
+
single `kill $PID` is enough.
|
| 84 |
+
- Start it in its own group (`setsid`) so `kill -- -$PGID` takes the workers with it.
|
| 85 |
+
- Check with `nvidia-smi` — if a PID still holds memory, `kill` **that exact numeric PID**, after
|
| 86 |
+
confirming its cmdline is **not** `claude` / `--print`.
|
| 87 |
+
|
| 88 |
+
## Rules of thumb
|
| 89 |
+
|
| 90 |
+
- **Never** match a task-prompt string (`server.py`, `train.py`, `build.sh`, `/app`, `python3`, …)
|
| 91 |
+
with `pkill -f`, `pgrep -f`, `killall`, `fuser`, or a `/proc` cmdline scan — they all can hit the
|
| 92 |
+
agent (its argv holds the prompt).
|
| 93 |
+
- **Always** kill a background job by the exact PID from its pidfile (or its PGID).
|
| 94 |
+
- If you must enumerate, match a **unique token not in the prompt** and **exclude `claude` / `--print`
|
| 95 |
+
and your own shell**; `pgrep -af` and look before you kill.
|
| 96 |
+
- `SIGTERM` first for a clean release; `-9` only as a last resort on a specific numeric PID.
|
tasks/video-sparse-attention/spatial-window-temporal-global/environment/docker-compose.yaml
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Anti-cheat firewall overlay, merged on top of Harbor's base compose. Gives the main container
|
| 2 |
+
# NET_ADMIN and runs restrict-network.sh as the entrypoint, so only DNS + the LLM API endpoints are
|
| 3 |
+
# reachable (pypi/github/HF blocked). network_mode stays "public" (see task.toml) — the firewall, not
|
| 4 |
+
# Docker, enforces the allowlist. mini-swe-agent is pre-installed and harbor's patched installer skips
|
| 5 |
+
# the (now-blocked) network install when it is already present.
|
| 6 |
+
services:
|
| 7 |
+
main:
|
| 8 |
+
cap_add:
|
| 9 |
+
- NET_ADMIN
|
| 10 |
+
entrypoint: ["/bin/bash", "/app/restrict-network.sh"]
|
| 11 |
+
environment:
|
| 12 |
+
- ALLOWED_HOSTS=${ALLOWED_HOSTS:-}
|
| 13 |
+
- FIREWORKS_BASE_URL=${FIREWORKS_BASE_URL:-}
|
| 14 |
+
- OPENROUTER_BASE_URL=${OPENROUTER_BASE_URL:-}
|
| 15 |
+
- OPENAI_BASE_URL=${OPENAI_BASE_URL:-}
|
| 16 |
+
- ANTHROPIC_BASE_URL=${ANTHROPIC_BASE_URL:-}
|
| 17 |
+
- LLM_BASE_URL=${LLM_BASE_URL:-}
|
| 18 |
+
- LITELLM_BASE_URL=${LITELLM_BASE_URL:-}
|
tasks/video-sparse-attention/spatial-window-temporal-global/environment/measure.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Self-assessment tool — your correctness + achieved TFLOP/s across a RANGE of shapes.
|
| 2 |
+
|
| 3 |
+
python /app/measure.py # the graded regime
|
| 4 |
+
python /app/measure.py --quick # smaller sizes for fast iteration
|
| 5 |
+
|
| 6 |
+
You are scored on the **geomean achieved TFLOP/s** — NOT one fixed size, and the leaderboard is UNCAPPED
|
| 7 |
+
(higher is always better). The shapes below are a DIFFERENT sample from the same regime the grader uses, so
|
| 8 |
+
optimize for GENERALITY. Work is counted with the same shape-only formula the grader uses, so the number
|
| 9 |
+
printed here is computed exactly as your score is.
|
| 10 |
+
|
| 11 |
+
GENERATED by _factory/build.py.
|
| 12 |
+
"""
|
| 13 |
+
import argparse
|
| 14 |
+
import math
|
| 15 |
+
import sys
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
|
| 19 |
+
sys.path.insert(0, "/app")
|
| 20 |
+
from reference import window_global_stride_attention as _ref
|
| 21 |
+
from win_global import window_global_stride_attention as _agent
|
| 22 |
+
|
| 23 |
+
TOL = 0.005
|
| 24 |
+
|
| 25 |
+
FULL = [(1, 24, 48, 80, 16, 128, 4, 8, 3, 3, 128), (1, 16, 48, 80, 24, 128, 4, 8, 3, 3, 96), (1, 24, 48, 80, 12, 128, 2, 8, 5, 3, 128), (1, 20, 48, 64, 24, 64, 4, 8, 3, 5, 96), (2, 12, 32, 64, 24, 128, 4, 8, 3, 3, 64)]
|
| 26 |
+
QUICK = [(1, 8, 24, 40, 8, 128, 4, 8, 3, 3, 48), (1, 12, 16, 40, 8, 64, 4, 8, 3, 3, 32), (1, 8, 24, 32, 8, 128, 4, 8, 3, 3, 48)]
|
| 27 |
+
|
| 28 |
+
def canonical_work(B, F, Hh, Ww, NH, D, TH, TW, WH, WW, STR):
|
| 29 |
+
"""FLOPs attributed to one forward, from the SHAPE ALONE.
|
| 30 |
+
|
| 31 |
+
Every query sees WH*WW spatial tiles of TS = TH*TW tokens inside its own frame (the window is clamped
|
| 32 |
+
inward, never truncated) plus (F-1)*S/STR strided keys drawn from the OTHER frames -- the two sets are
|
| 33 |
+
disjoint by construction. Each pair costs 4*D FLOPs.
|
| 34 |
+
"""
|
| 35 |
+
TS = TH * TW
|
| 36 |
+
S = Hh * Ww
|
| 37 |
+
keys = WH * WW * TS + (F - 1) * (S // STR)
|
| 38 |
+
return 4 * D * B * NH * (F * S) * keys
|
| 39 |
+
|
| 40 |
+
def _mk(B, F, Hh, Ww, NH, D, TH, TW, WH, WW, STR, seed):
|
| 41 |
+
gen = torch.Generator(device="cuda").manual_seed(seed)
|
| 42 |
+
T = F * Hh * Ww
|
| 43 |
+
def r():
|
| 44 |
+
return torch.randn(B, T, NH, D, device="cuda", dtype=torch.bfloat16, generator=gen)
|
| 45 |
+
return r(), r(), r(), (F, Hh, Ww), (TH, TW), (WH, WW), STR
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _is_exact(t):
|
| 49 |
+
"""Integer/bool tensors are compared EXACTLY: .float() is lossy above 2**24, so two distinct large
|
| 50 |
+
ids (page ids, token ids, indices) can compare equal and let a wrong kernel pass."""
|
| 51 |
+
return t.dtype in (torch.int8, torch.int16, torch.int32, torch.int64, torch.uint8, torch.bool)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _check(out, ref):
|
| 55 |
+
"""-> (ok, value, msg). Exact for integer/bool; relative Frobenius error otherwise."""
|
| 56 |
+
if out is None or tuple(out.shape) != tuple(ref.shape):
|
| 57 |
+
return False, 1.0, "bad/None shape"
|
| 58 |
+
if _is_exact(ref):
|
| 59 |
+
bad = int((out != ref).sum())
|
| 60 |
+
return bad == 0, float(bad), ("exact match" if bad == 0 else f"{bad} elements differ")
|
| 61 |
+
e = float((out.float() - ref.float()).norm() / (ref.float().norm() + 1e-12))
|
| 62 |
+
return e <= TOL, e, f"relerr {e:.2e}"
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _bench(fn, reps=8, warm=3):
|
| 66 |
+
for _ in range(warm):
|
| 67 |
+
fn()
|
| 68 |
+
torch.cuda.synchronize()
|
| 69 |
+
best = float("inf")
|
| 70 |
+
for _ in range(reps):
|
| 71 |
+
s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
|
| 72 |
+
s.record()
|
| 73 |
+
fn()
|
| 74 |
+
e.record()
|
| 75 |
+
torch.cuda.synchronize()
|
| 76 |
+
best = min(best, s.elapsed_time(e))
|
| 77 |
+
return best / 1e3
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def main():
|
| 81 |
+
ap = argparse.ArgumentParser()
|
| 82 |
+
ap.add_argument("--quick", action="store_true")
|
| 83 |
+
a = ap.parse_args()
|
| 84 |
+
shapes = QUICK if a.quick else FULL
|
| 85 |
+
print(f"geomean over {len(shapes)} shapes ({'quick' if a.quick else 'full'}); the grader uses "
|
| 86 |
+
f"DIFFERENT sizes in the same regime — optimize for generality\n")
|
| 87 |
+
vals, allok = [], True
|
| 88 |
+
for shp in shapes:
|
| 89 |
+
args = _mk(*shp, seed=sum(int(x) for x in shp) % 9973)
|
| 90 |
+
ref = _ref(*args)
|
| 91 |
+
try:
|
| 92 |
+
out = _agent(*args)
|
| 93 |
+
except Exception as ex:
|
| 94 |
+
print(f" {shp}: RAISED {type(ex).__name__}: {str(ex)[:70]}")
|
| 95 |
+
allok = False
|
| 96 |
+
continue
|
| 97 |
+
ok, val, msg = _check(out, ref)
|
| 98 |
+
allok = allok and ok
|
| 99 |
+
t = _bench(lambda: _agent(*args))
|
| 100 |
+
v = canonical_work(*shp) / t / 1e12 if t > 0 else 0.0
|
| 101 |
+
vals.append(v)
|
| 102 |
+
print(f" {str(shp):28s} {t*1e3:9.2f} ms | {v:9.2f} TFLOP/s | {msg} {'ok' if ok else 'FAIL'}")
|
| 103 |
+
del args, ref, out
|
| 104 |
+
torch.cuda.empty_cache()
|
| 105 |
+
geo = math.exp(sum(math.log(max(v, 1e-9)) for v in vals) / len(vals)) if vals else 0.0
|
| 106 |
+
print(f"\n => GEOMEAN {geo:.2f} TFLOP/s "
|
| 107 |
+
f"({'all correct' if allok else 'SOME WRONG — a wrong kernel scores 0, fix correctness first'})")
|
| 108 |
+
print(" This IS your score, and it is uncapped — higher is always better. Keep pushing.")
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
if __name__ == "__main__":
|
| 112 |
+
main()
|
tasks/video-sparse-attention/spatial-window-temporal-global/environment/reference.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Reference implementation — the CORRECTNESS SPEC for `window_global_stride_attention`.
|
| 2 |
+
|
| 3 |
+
This is correct but slow. It defines exactly what your kernel must reproduce; its speed has no
|
| 4 |
+
bearing on your score, which is an absolute TFLOP/s number. GENERATED by _factory/build.py.
|
| 5 |
+
"""
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def window_global_stride_attention(q, k, v, latent, tile, window, stride, scale=None):
|
| 10 |
+
"""In-frame tile window + strided sample of the other frames, as an explicit gather in fp32.
|
| 11 |
+
|
| 12 |
+
Correct and simple — it is the numerical SPECIFICATION, not a performance target. It gathers the whole
|
| 13 |
+
window of every query tile and the whole global set of every query frame and softmaxes them densely.
|
| 14 |
+
"""
|
| 15 |
+
B, T, NH, D = q.shape
|
| 16 |
+
F, Hh, Ww = latent
|
| 17 |
+
th, tw = tile
|
| 18 |
+
wh, ww = window
|
| 19 |
+
nsh, nsw = Hh // th, Ww // tw
|
| 20 |
+
nsp = nsh * nsw
|
| 21 |
+
TS = th * tw
|
| 22 |
+
NW = wh * ww
|
| 23 |
+
S = Hh * Ww
|
| 24 |
+
if scale is None:
|
| 25 |
+
scale = D ** -0.5
|
| 26 |
+
dev = q.device
|
| 27 |
+
|
| 28 |
+
def to_tiles(x):
|
| 29 |
+
return (x.view(B, F, nsh, th, nsw, tw, NH, D)
|
| 30 |
+
.permute(0, 1, 2, 4, 3, 5, 6, 7)
|
| 31 |
+
.reshape(B, F, nsp, TS, NH, D))
|
| 32 |
+
|
| 33 |
+
qt, kt, vt = to_tiles(q.float()), to_tiles(k.float()), to_tiles(v.float())
|
| 34 |
+
kf, vf = k.float(), v.float()
|
| 35 |
+
ot = torch.empty(B, F, nsp, TS, NH, D, device=dev, dtype=torch.float32)
|
| 36 |
+
|
| 37 |
+
sp = torch.arange(nsp, device=dev)
|
| 38 |
+
sh = (sp // nsw - wh // 2).clamp(0, nsh - wh)
|
| 39 |
+
sw = (sp % nsw - ww // 2).clamp(0, nsw - ww)
|
| 40 |
+
ih = sh[:, None] + torch.arange(wh, device=dev)
|
| 41 |
+
iw = sw[:, None] + torch.arange(ww, device=dev)
|
| 42 |
+
wt = (ih[:, :, None] * nsw + iw[:, None, :]).reshape(nsp, NW) # (nsp, wh*ww) tile ids
|
| 43 |
+
|
| 44 |
+
off = torch.arange(0, S, stride, device=dev) # sampled offsets inside a frame
|
| 45 |
+
step = max(1, int(4e8) // max(1, (NW * TS + (F - 1) * off.numel()) * NH * D * 4))
|
| 46 |
+
for f in range(F):
|
| 47 |
+
other = torch.tensor([x for x in range(F) if x != f], device=dev, dtype=torch.long)
|
| 48 |
+
gidx = (other[:, None] * S + off[None, :]).reshape(-1) # global keys of this query frame
|
| 49 |
+
kg, vg = kf[:, gidx], vf[:, gidx] # (B, NG, NH, D)
|
| 50 |
+
for s0 in range(0, nsp, step):
|
| 51 |
+
e0 = min(nsp, s0 + step)
|
| 52 |
+
g = wt[s0:e0]
|
| 53 |
+
kc = torch.cat([kt[:, f][:, g].reshape(B, e0 - s0, NW * TS, NH, D),
|
| 54 |
+
kg.unsqueeze(1).expand(B, e0 - s0, gidx.numel(), NH, D)], dim=2)
|
| 55 |
+
vc = torch.cat([vt[:, f][:, g].reshape(B, e0 - s0, NW * TS, NH, D),
|
| 56 |
+
vg.unsqueeze(1).expand(B, e0 - s0, gidx.numel(), NH, D)], dim=2)
|
| 57 |
+
qc = qt[:, f, s0:e0] * scale
|
| 58 |
+
s = torch.einsum("bcqhd,bckhd->bchqk", qc, kc)
|
| 59 |
+
ot[:, f, s0:e0] = torch.einsum("bchqk,bckhd->bcqhd", torch.softmax(s, dim=-1), vc)
|
| 60 |
+
|
| 61 |
+
return (ot.reshape(B, F, nsh, nsw, th, tw, NH, D)
|
| 62 |
+
.permute(0, 1, 2, 4, 3, 5, 6, 7).reshape(B, T, NH, D))
|
tasks/video-sparse-attention/spatial-window-temporal-global/environment/restrict-network.sh
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Outbound firewall (anti-cheat): allow ONLY DNS, loopback, docker-internal networks, and the LLM API
|
| 3 |
+
# endpoints the agent needs. Everything else is dropped — in particular pypi, github, and huggingface,
|
| 4 |
+
# so the agent cannot `pip install vllm` / `pip install sglang` / clone the reference moe_align kernel and
|
| 5 |
+
# copy it. torch + triton are already in the image, and mini-swe-agent is pre-installed (harbor's patched
|
| 6 |
+
# installer skips the network install when it is already present), so no package index is needed at run time.
|
| 7 |
+
#
|
| 8 |
+
# Runs as the container ENTRYPOINT before the CMD. iptables rules are network-namespace-wide, so they also
|
| 9 |
+
# apply to the agent's `docker exec` commands. Requires cap_add: NET_ADMIN.
|
| 10 |
+
set -uo pipefail
|
| 11 |
+
|
| 12 |
+
# LLM API endpoints the agent may reach. Extend at launch via ALLOWED_HOSTS=host1,host2 (no scheme).
|
| 13 |
+
API_HOSTS=(
|
| 14 |
+
api.fireworks.ai
|
| 15 |
+
openrouter.ai openrouter.io
|
| 16 |
+
api.openai.com api.anthropic.com generativelanguage.googleapis.com
|
| 17 |
+
api.together.xyz integrate.api.nvidia.com api.moonshot.cn api.kimi.com
|
| 18 |
+
)
|
| 19 |
+
# Auto-allow hosts from any *_BASE_URL / *_ENDPOINT env var (ANTHROPIC_BASE_URL, OPENAI_BASE_URL, …).
|
| 20 |
+
CUSTOM=()
|
| 21 |
+
while IFS='=' read -r n v; do
|
| 22 |
+
case "$n" in
|
| 23 |
+
*_BASE_URL|*_URL|*_ENDPOINT)
|
| 24 |
+
[ -n "$v" ] && CUSTOM+=("$(echo "$v" | sed 's|.*://||; s|[:/].*||')") ;;
|
| 25 |
+
esac
|
| 26 |
+
done < <(env)
|
| 27 |
+
if [ -n "${ALLOWED_HOSTS:-}" ]; then IFS=',' read -ra E <<< "$ALLOWED_HOSTS"; CUSTOM+=("${E[@]}"); fi
|
| 28 |
+
ALL_HOSTS=("${API_HOSTS[@]}" ${CUSTOM[@]+"${CUSTOM[@]}"})
|
| 29 |
+
|
| 30 |
+
if iptables -L OUTPUT -n >/dev/null 2>&1; then
|
| 31 |
+
echo "restrict-network: applying outbound allowlist firewall..."
|
| 32 |
+
iptables -F OUTPUT 2>/dev/null || true
|
| 33 |
+
iptables -A OUTPUT -o lo -j ACCEPT
|
| 34 |
+
iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
|
| 35 |
+
iptables -A OUTPUT -p udp --dport 53 -j ACCEPT
|
| 36 |
+
iptables -A OUTPUT -p tcp --dport 53 -j ACCEPT
|
| 37 |
+
iptables -A OUTPUT -d 10.0.0.0/8 -j ACCEPT
|
| 38 |
+
iptables -A OUTPUT -d 172.16.0.0/12 -j ACCEPT
|
| 39 |
+
iptables -A OUTPUT -d 192.168.0.0/16 -j ACCEPT
|
| 40 |
+
iptables -A OUTPUT -d 127.0.0.11 -j ACCEPT
|
| 41 |
+
for h in "${ALL_HOSTS[@]}"; do
|
| 42 |
+
for ip in $(getent ahosts "$h" 2>/dev/null | awk '{print $1}' | sort -u); do
|
| 43 |
+
iptables -A OUTPUT -d "$ip" -j ACCEPT
|
| 44 |
+
done
|
| 45 |
+
done
|
| 46 |
+
iptables -A OUTPUT -j REJECT --reject-with icmp-admin-prohibited
|
| 47 |
+
echo "restrict-network: outbound locked to DNS + LLM endpoints; pypi/github/HF blocked."
|
| 48 |
+
else
|
| 49 |
+
echo "restrict-network: WARNING — iptables unavailable (need cap_add NET_ADMIN); NOT firewalled." >&2
|
| 50 |
+
fi
|
| 51 |
+
|
| 52 |
+
exec "$@"
|
tasks/video-sparse-attention/spatial-window-temporal-global/environment/win_global.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Your implementation goes here.
|
| 2 |
+
|
| 3 |
+
Replace the body of `window_global_stride_attention` with a FAST implementation that reproduces the output of /app/reference.py
|
| 4 |
+
(same signature, same numerics within tolerance) but is much faster — see /app/instruction.md.
|
| 5 |
+
Run `python /app/measure.py` to check your correctness and achieved TFLOP/s.
|
| 6 |
+
|
| 7 |
+
You may add helper modules, Triton kernels, CUDA extensions, caches, etc. — only this function's name,
|
| 8 |
+
signature and returned value are fixed by the contract.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def window_global_stride_attention(q, k, v, latent, tile, window, stride, scale=None):
|
| 13 |
+
"""In-frame spatial window + strided global attention.
|
| 14 |
+
|
| 15 |
+
Args:
|
| 16 |
+
q, k, v: (B, T, NH, D) bfloat16 — T = F*Hh*Ww tokens in RASTER order.
|
| 17 |
+
latent: (F, Hh, Ww) tuple of int — latent frames / height / width.
|
| 18 |
+
tile: (th, tw) tuple of int — 2D SPATIAL tile; divides (Hh, Ww) exactly.
|
| 19 |
+
window: (wh, ww) tuple of int — in-frame window measured in spatial TILES, both odd.
|
| 20 |
+
stride: int — global sampling stride within a frame; divides S = Hh*Ww exactly.
|
| 21 |
+
scale: float or None — logit scale; None means D ** -0.5.
|
| 22 |
+
|
| 23 |
+
Returns:
|
| 24 |
+
o: (B, T, NH, D), bfloat16 or float32 — must match /app/reference.py numerically.
|
| 25 |
+
"""
|
| 26 |
+
raise NotImplementedError("Implement a fast window_global_stride_attention in /app/win_global.py")
|
tasks/video-sparse-attention/spatial-window-temporal-global/instruction.md
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Write a fast spatial-window + strided-global video attention kernel
|
| 2 |
+
|
| 3 |
+
You are given a **correct but slow** reference at **`/app/reference.py`** — `window_global_stride_attention(q, k, v, latent, tile, window, stride, scale=None)`. **Read it, run it, profile it.**
|
| 4 |
+
|
| 5 |
+
Write **`/app/win_global.py`** with the **same signature** and the **same numerical output**, but **as fast as you can make it**.
|
| 6 |
+
|
| 7 |
+
```python
|
| 8 |
+
def window_global_stride_attention(q, k, v, latent, tile, window, stride, scale=None):
|
| 9 |
+
...
|
| 10 |
+
```
|
| 11 |
+
|
| 12 |
+
## The computation (this is the exact spec)
|
| 13 |
+
|
| 14 |
+
The sequence is a 3D latent in **raster order** (`i = (f*Hh + h)*Ww + w`, `T = F*S`,
|
| 15 |
+
`S = Hh*Ww`), and each frame's spatial plane is cut into 2D tiles of size `(th, tw)`:
|
| 16 |
+
`nsh*nsw = (Hh/th)*(Ww/tw)` tiles of `TS = th*tw` tokens, with flat spatial-tile index
|
| 17 |
+
`sp = (h//th)*nsw + (w//tw)`.
|
| 18 |
+
|
| 19 |
+
A query in frame `f`, spatial tile `sp = bh*nsw + bw`, attends to the union of two **disjoint** sets:
|
| 20 |
+
|
| 21 |
+
```
|
| 22 |
+
A) the IN-FRAME WINDOW: the (wh x ww) block of spatial tiles of frame f starting at
|
| 23 |
+
sh = clamp(bh - wh//2, 0, nsh - wh), sw = clamp(bw - ww//2, 0, nsw - ww)
|
| 24 |
+
-> wh*ww tiles = wh*ww*TS tokens, all inside frame f (clamped inward, never truncated)
|
| 25 |
+
|
| 26 |
+
B) the STRIDED GLOBAL SET: every stride-th token of every OTHER frame,
|
| 27 |
+
{ fk*S + m*stride : fk in [0, F), fk != f, m in [0, S/stride) }
|
| 28 |
+
-> (F-1) * (S/stride) tokens
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
`stride` divides `S` exactly, and the sample always starts at offset `0` inside each frame. The two sets are
|
| 32 |
+
disjoint because A lives entirely in frame `f` and B excludes frame `f`, so there is nothing to
|
| 33 |
+
de-duplicate — but the exclusion of the query's own frame from B **is part of the specification**: including
|
| 34 |
+
it would add `S/stride` extra keys, most of which are already inside the window.
|
| 35 |
+
|
| 36 |
+
Then one softmax over the union:
|
| 37 |
+
|
| 38 |
+
```
|
| 39 |
+
logit(i, j) = scale * (q_i . k_j) for j in A(i) UNION B(i)
|
| 40 |
+
o_i = softmax_j( logit(i, j) ) @ v
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
with `scale` defaulting to `D ** -0.5`. Bidirectional, no causal mask, no bias, no reweighting: the global
|
| 44 |
+
keys are ordinary keys and get no boost for "representing" the tokens they were sampled from.
|
| 45 |
+
|
| 46 |
+
Two things worth internalising:
|
| 47 |
+
|
| 48 |
+
* **B depends only on the query's frame**, not on its spatial position, so all `S` queries of a frame share
|
| 49 |
+
the same `(F-1)*S/stride` global keys — thousands of queries against one key block.
|
| 50 |
+
* **A depends only on the query's spatial tile**, not on its frame, up to the frame offset — so the *shape*
|
| 51 |
+
of the window gather is the same in every frame.
|
| 52 |
+
|
| 53 |
+
`/app/reference.py` gathers the whole window of every query tile and the whole global set of every query
|
| 54 |
+
frame and softmaxes them densely. That is the exact specification; it is deliberately simple rather than
|
| 55 |
+
fast.
|
| 56 |
+
|
| 57 |
+
## The contract (fixed — do not change these)
|
| 58 |
+
|
| 59 |
+
| arg | shape | dtype | meaning |
|
| 60 |
+
|-----|-------|-------|---------|
|
| 61 |
+
| `q`, `k`, `v` | `(B, T, NH, D)` | `bfloat16` | raster-ordered over the latent |
|
| 62 |
+
| `latent` | 3-tuple | `int` | `(F, Hh, Ww)`; `T == F*Hh*Ww` |
|
| 63 |
+
| `tile` | 2-tuple | `int` | `(th, tw)`; divides `(Hh, Ww)` exactly; `TS = th*tw` is 16-64 |
|
| 64 |
+
| `window` | 2-tuple | `int` | `(wh, ww)` in spatial **tiles**, both odd, `wh <= Hh/th`, `ww <= Ww/tw` |
|
| 65 |
+
| `stride` | scalar | `int` | global sampling stride; **divides `S = Hh*Ww` exactly**, 16-128 |
|
| 66 |
+
| `scale` | scalar | `float` or `None` | logit scale; `None` means `D ** -0.5` |
|
| 67 |
+
|
| 68 |
+
**Return** `o` of shape `(B, T, NH, D)` in the same raster order as `q`, dtype `bfloat16` or `float32`.
|
| 69 |
+
|
| 70 |
+
All of `latent`, `tile`, `window`, `stride` are **host-side Python values**, so the whole mask is known
|
| 71 |
+
before launch — there is no device-side indirection anywhere in this task.
|
| 72 |
+
|
| 73 |
+
`window` may be `(1, 3)` (one correctness shape is). All tensors are CUDA, contiguous, **read-only**. No GQA,
|
| 74 |
+
no causality, no RoPE, no dropout, no bias.
|
| 75 |
+
|
| 76 |
+
**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): the real
|
| 77 |
+
video latents — `F x Hh x Ww` from `16 x 32 x 64` to `32 x 48 x 80` (33k-123k tokens), `NH` in 12-24, `D` in
|
| 78 |
+
{64, 128}, `tile` `(4,8)` or `(2,8)`, `window` `(3,3)`, `(5,3)` or `(3,5)` tiles, `stride` in {64, 96, 128},
|
| 79 |
+
`B` in 1-2.
|
| 80 |
+
|
| 81 |
+
That is a few hundred window keys plus one to two thousand global keys — around 1-3% of dense. The two
|
| 82 |
+
branches are of comparable size, so **both** of them matter to the answer and to the score: the work formula
|
| 83 |
+
credits `wh*ww*TS + (F-1)*S/stride` keys per query and nothing else.
|
| 84 |
+
|
| 85 |
+
## How success is decided (runs on GPU)
|
| 86 |
+
|
| 87 |
+
**1. Correctness — a required gate.** Your output must match the reference (evaluated in fp32 as a stable ground truth)
|
| 88 |
+
within **relative Frobenius error `5e-3`** at every graded shape, including the timed ones.
|
| 89 |
+
|
| 90 |
+
The gate is measured. **Noise floor:** two independent implementations agree with the reference to
|
| 91 |
+
**`4.3e-7`** and **`4.9e-7`** — a single dense masked softmax over the raster sequence with the whole key set
|
| 92 |
+
expressed as a per-token boolean predicate (no tile permute, no per-frame gather, no chunking), and a
|
| 93 |
+
flash-style streaming online softmax over 256-key raster tiles, which visits the in-frame and cross-frame
|
| 94 |
+
keys *interleaved* instead of concatenated as the reference does. So neither the geometry nor the
|
| 95 |
+
concatenation order costs anything. The floor is the dtypes: rounding `P` and `V` to bf16 for the `P@V` GEMM
|
| 96 |
+
and returning `o` in bf16 measures **`2.36e-3`**, and the gate is **2.1x** that.
|
| 97 |
+
|
| 98 |
+
**Discrimination:** dropping the temporal-global branch and attending only inside the query's own frame
|
| 99 |
+
scores **`1.05`**; dropping the spatial window and attending to the whole query frame scores **`0.74`**;
|
| 100 |
+
keeping both branches but ignoring `stride` and taking every token of the other frames scores **`0.97`**.
|
| 101 |
+
All three are 150-200x above the gate. A wrong kernel scores **0**, no matter how fast.
|
| 102 |
+
|
| 103 |
+
**2. Performance — this is your score, and it is an UNCAPPED leaderboard.**
|
| 104 |
+
|
| 105 |
+
```
|
| 106 |
+
reward = geomean over graded shapes of ( canonical_work(shape) / your_runtime ) [TFLOP/s]
|
| 107 |
+
reward = 0 if the submission is wrong at any graded shape
|
| 108 |
+
```
|
| 109 |
+
|
| 110 |
+
`canonical_work` depends **only on the shape**, never on how you implemented it, so every submission is
|
| 111 |
+
credited the same work and this is a pure speed ranking in useful units:
|
| 112 |
+
|
| 113 |
+
```
|
| 114 |
+
TS = th*tw ; S = Hh*Ww ; T = F*S
|
| 115 |
+
keys = wh*ww*TS + (F-1) * (S // stride) # in-frame window + strided sample of the OTHER frames
|
| 116 |
+
FLOPs = 4 * D * B * NH * T * keys # 2*D for q.k + 2*D for p*v
|
| 117 |
+
```
|
| 118 |
+
|
| 119 |
+
**There is no cap and no target.** Higher TFLOP/s is always a strictly better score, so **push the
|
| 120 |
+
performance as hard as you can**. Getting a correct implementation is the *start* of the task, not the end of
|
| 121 |
+
it. Once correct, spend the entire remainder of your budget profiling and optimising, re-checking correctness
|
| 122 |
+
after every change. **Use your full time budget.**
|
| 123 |
+
|
| 124 |
+
Run **`python /app/measure.py`** at any point to see your per-shape and geomean TFLOP/s plus correctness.
|
| 125 |
+
|
| 126 |
+
## Where the performance comes from
|
| 127 |
+
|
| 128 |
+
**The global set is shared by a whole frame** — `S` queries (1500-4000 of them) against the
|
| 129 |
+
same `(F-1)*S/stride` keys. That is the dominant structure: make the threadblock own a `(frame, head)` pair
|
| 130 |
+
(or a range of query tiles within one frame) and stream the global block once, keeping it in shared memory a
|
| 131 |
+
tile at a time while all of that frame's query tiles pass over it. A kernel that re-reads the global block
|
| 132 |
+
per query tile does `nsp` times the traffic it needs to.
|
| 133 |
+
|
| 134 |
+
**The global gather is a stride-`s` comb over the whole sequence**, one element every `stride` tokens, i.e.
|
| 135 |
+
one `D`-wide contiguous row every `stride*NH*D` elements. Vectorise along `D` (a full 128- or 256-byte row per
|
| 136 |
+
key) so each key is one or two coalesced transactions; do *not* let a warp span multiple sampled keys with a
|
| 137 |
+
strided thread mapping. Since the sampled offsets are identical in every frame, the whole comb is
|
| 138 |
+
`(F-1)` copies of one address pattern shifted by `S` — cheap to generate and perfectly prefetchable.
|
| 139 |
+
|
| 140 |
+
**Skipping the query's own frame** turns the comb into two contiguous ranges of frames (`[0, f)` and
|
| 141 |
+
`(f, F)`), not a predicated walk. Emit it as two loops.
|
| 142 |
+
|
| 143 |
+
**The window is the cheap branch** but it is where the reuse is: adjacent query tiles along `w` share
|
| 144 |
+
`(ww-1)/ww` of their window tiles, and at a frame edge the clamp makes several query tiles share the *same*
|
| 145 |
+
window. One threadblock per row of query tiles amortises it.
|
| 146 |
+
|
| 147 |
+
**One softmax.** Run branch A then branch B (or the reverse) inside a single online-softmax loop. Two
|
| 148 |
+
separate attentions followed by an average is simply wrong; two separate attentions followed by a correct
|
| 149 |
+
log-sum-exp merge is right but costs an extra pass over `o` for no reason.
|
| 150 |
+
|
| 151 |
+
Do not materialise a mask: `T` reaches 123k.
|
| 152 |
+
|
| 153 |
+
## Precision and faithfulness (read this)
|
| 154 |
+
|
| 155 |
+
Inputs are **bfloat16**; the output may be bf16 or fp32. Matmuls on bf16 tensor cores with
|
| 156 |
+
**fp32 accumulation**; online-softmax state (running max, running sum, output accumulator) in **fp32**. The
|
| 157 |
+
reduction is 1000-3000 keys long — enough that a bf16 running sum is visible in the norm, and it is *longer*
|
| 158 |
+
for queries in clips with more frames, so the error would grow with `F`.
|
| 159 |
+
|
| 160 |
+
The tolerance is **`5e-3`**, measured rather than inherited. In fp32 the computation is reproducible to
|
| 161 |
+
**`~5e-7`** by two independent implementations (see the correctness section), so nothing about the two-branch
|
| 162 |
+
key set costs accuracy. What sets the floor is rounding `P` and `V` to bf16 for the second GEMM and returning
|
| 163 |
+
`o` in bf16: **`2.36e-3`**, and the gate is 2.1x that.
|
| 164 |
+
|
| 165 |
+
**fp8** is acceptable only if you can hold `5e-3`; on a structurally identical task, per-tensor e4m3
|
| 166 |
+
quantisation of `Q` and `K` measured `4.0e-2`, so it does not hold by default.
|
| 167 |
+
|
| 168 |
+
The global sample is **exactly** every `stride`-th token starting at offset `0` of each frame other than the
|
| 169 |
+
query's own. Do not re-phase the sample per frame, do not round `S/stride` to a convenient tile count, and do
|
| 170 |
+
not include the query's own frame "for symmetry" — each of those changes the set of terms in the denominator,
|
| 171 |
+
a systematic error that grows with `F`, not a rounding difference.
|
| 172 |
+
|
| 173 |
+
Do **not** infer from the reference that fp32 compute is wanted; it runs in fp32 purely to be a stable
|
| 174 |
+
numerical *specification*.
|
| 175 |
+
|
| 176 |
+
### What the tolerance does NOT permit
|
| 177 |
+
|
| 178 |
+
The tolerance exists **only** to absorb low-precision arithmetic noise. You are responsible for a **faithful
|
| 179 |
+
implementation of the specified computation**. It is not a budget to spend on approximation. The following
|
| 180 |
+
are wrong answers even if they happen to land inside the tolerance at some shape:
|
| 181 |
+
|
| 182 |
+
- changing the algorithm to something that merely *approximates* the spec (dropping terms, truncating a
|
| 183 |
+
series, low-rank or sketched substitutes, skipping a correction term);
|
| 184 |
+
- shortening the computation (fewer iterations/steps than specified, early exit on a heuristic, subsampling
|
| 185 |
+
or striding over the sequence, ignoring positions whose contribution "looks small");
|
| 186 |
+
- computing at a coarser granularity than the spec (sharing a decay, scale, or normaliser across positions
|
| 187 |
+
that the spec gives their own);
|
| 188 |
+
- anything whose error **grows** with sequence length, batch, or head count.
|
| 189 |
+
|
| 190 |
+
A faithful bf16/fp8 kernel's error is *noise*: it stays flat as the problem grows and sits an order of
|
| 191 |
+
magnitude below the gate. An approximation's error is *bias*: it scales with the problem. The graded shapes
|
| 192 |
+
are deliberately large, so the difference shows up.
|
| 193 |
+
|
| 194 |
+
## What's available
|
| 195 |
+
|
| 196 |
+
- **Triton 3.6** (with Gluon), **CUDA C++ via `nvcc`** (`torch.utils.cpp_extension.load` for an inline
|
| 197 |
+
extension), header-only **CUTLASS** at `/opt/cutlass/include`, and the **CuTe DSL**
|
| 198 |
+
(`nvidia-cutlass-dsl`). C++ / CuTe DSL is the encouraged route; Triton is fully supported.
|
| 199 |
+
- `torch` 2.11 (CUDA 12.8) and `einops` for bookkeeping.
|
| 200 |
+
- A GPU with compute capability sm≥90 (Hopper or newer).
|
| 201 |
+
- **No internet access.** `pip install` and cloning repos are blocked. Everything you are permitted to use is
|
| 202 |
+
already installed, and no library implementation of this kernel exists on the machine.
|
| 203 |
+
- Manage any long-running background job (a build, an `ncu`/`nsys` profile) by its **recorded PID** — see
|
| 204 |
+
`/app/CLAUDE.md` and `/app/PROCESS_MANAGEMENT.md`.
|
| 205 |
+
|
| 206 |
+
## How the grading actually runs (so there are no surprises)
|
| 207 |
+
|
| 208 |
+
- **`/app/win_global.py` is the only file that is graded.** The grader imports `window_global_stride_attention` from it and reads nothing
|
| 209 |
+
else from `/app`.
|
| 210 |
+
- **The grader is not on this machine while you work.** It is copied in only after your session ends and it
|
| 211 |
+
carries its **own private copy of the reference** and its own input generator. Editing `/app/reference.py`
|
| 212 |
+
or `/app/measure.py` is allowed — they are yours to experiment with — but it has **no effect whatsoever on
|
| 213 |
+
your score**. Do not spend budget on them.
|
| 214 |
+
- **Every timed repetition uses freshly generated inputs**, and the output of a timed call is itself checked
|
| 215 |
+
against the reference. Caching or memoizing a result and replaying it fails the correctness gate rather
|
| 216 |
+
than producing a fast measurement. Ordinary shape-keyed JIT/autotune caching is fine and is not penalised.
|
| 217 |
+
- **The timed shapes are correctness-checked too.** Being correct only at the small shapes scores **0**.
|
| 218 |
+
- Inputs are random each grade and the graded shapes are not the ones in `measure.py`.
|
tasks/video-sparse-attention/spatial-window-temporal-global/task.toml
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
schema_version = "1.1"
|
| 2 |
+
|
| 3 |
+
[task]
|
| 4 |
+
name = "mle-bench/spatial-window-temporal-global"
|
| 5 |
+
description = "Local in space, global in time: every token attends densely inside a small window of its own frame, and additionally to a uniform stride-`s` sample of every OTHER frame, so the whole clip stays visible for a few percent of the keys. Two gathers with opposite characters — a short 2D box with row stride Ww, and a long stride-`s` comb spanning the entire sequence — sharing one softmax, plus a boundary rule that keeps the two sets disjoint."
|
| 6 |
+
authors = []
|
| 7 |
+
keywords = ["mle", "kernel-generation", "attention", "sparse-attention", "video-diffusion", "global-tokens", "strided-gather", "hunyuanvideo", "wan"]
|
| 8 |
+
|
| 9 |
+
[metadata]
|
| 10 |
+
suite = "mle-bench"
|
| 11 |
+
group = "kernel-generation"
|
| 12 |
+
level = "1.0"
|
| 13 |
+
difficulty = "hard"
|
| 14 |
+
category = "mle"
|
| 15 |
+
tags = [ "mle", "kernel-generation", "kernels", "gpu", "real-world",]
|
| 16 |
+
|
| 17 |
+
[verifier]
|
| 18 |
+
timeout_sec = 1800.0
|
| 19 |
+
|
| 20 |
+
[agent]
|
| 21 |
+
timeout_sec = 14400.0
|
| 22 |
+
|
| 23 |
+
# GPU request: honored by Modal/GKE/Daytona. On the local docker backend set environment.override_gpus: 0
|
| 24 |
+
# in the job config and attach a GPU via configs/gpu_overlay_nvidia.yaml (see RUNNING.md §5).
|
| 25 |
+
[environment]
|
| 26 |
+
build_timeout_sec = 3600.0
|
| 27 |
+
cpus = 8
|
| 28 |
+
memory_mb = 65536
|
| 29 |
+
storage_mb = 40960
|
| 30 |
+
gpus = 1
|
| 31 |
+
network_mode = "public"
|
| 32 |
+
mcp_servers = []
|
| 33 |
+
|
| 34 |
+
[verifier.env]
|
| 35 |
+
|
| 36 |
+
[environment.env]
|
| 37 |
+
|
| 38 |
+
[solution.env]
|
tasks/video-sparse-attention/spatial-window-temporal-global/tests/test.sh
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# GENERATED by _factory/build.py. python3 (not python): some CUDA bases lack the symlink.
|
| 3 |
+
set -u
|
| 4 |
+
mkdir -p /logs/verifier
|
| 5 |
+
python3 /tests/verify_env.py
|
tasks/video-sparse-attention/spatial-window-temporal-global/tests/verify_env.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""spatial-window-temporal-global verifier — correctness gate + achieved-TFLOP/s SPEED LEADERBOARD (uncapped).
|
| 2 |
+
|
| 3 |
+
reward = 0 if the submission is incorrect
|
| 4 |
+
reward = geomean over graded shapes of TFLOP/s otherwise
|
| 5 |
+
|
| 6 |
+
GENERATED by _factory/build.py — do not edit here; edit the spec and regenerate.
|
| 7 |
+
|
| 8 |
+
There is no gold solution and no oracle: the score is an absolute hardware metric, so it is hardware-portable
|
| 9 |
+
by construction and nothing has to be vendored, sealed, or re-benchmarked.
|
| 10 |
+
|
| 11 |
+
CORRECTNESS is a hard gate, checked against an INDEPENDENT (embedded) copy of the reference at every graded
|
| 12 |
+
shape including the timed ones, so editing /app/reference.py cannot affect grading and a fast wrong kernel
|
| 13 |
+
scores 0.
|
| 14 |
+
|
| 15 |
+
ANTI-CHEAT on the timing path: every timed rep runs on FRESHLY generated inputs, and the output of the last
|
| 16 |
+
timed rep is itself validated against the reference for those exact inputs. A submission that memoizes a
|
| 17 |
+
result and replays it fails the gate instead of posting an inflated number. Warm-up runs on a separate
|
| 18 |
+
throwaway input set, so ordinary shape-keyed JIT/autotune caching is not penalised.
|
| 19 |
+
|
| 20 |
+
WORK is attributed by a CANONICAL formula that depends only on the shape, never on the implementation, so all
|
| 21 |
+
submissions are credited identically and the ranking is a pure speed ranking.
|
| 22 |
+
"""
|
| 23 |
+
import importlib.util
|
| 24 |
+
import json
|
| 25 |
+
import math
|
| 26 |
+
import os
|
| 27 |
+
import sys
|
| 28 |
+
import traceback
|
| 29 |
+
|
| 30 |
+
import torch
|
| 31 |
+
|
| 32 |
+
REWARD_DIR = "/logs/verifier"
|
| 33 |
+
MODULE_PATH = "/app/win_global.py"
|
| 34 |
+
TOL = 0.005
|
| 35 |
+
|
| 36 |
+
GRADER_SHAPES = [(1, 32, 48, 80, 16, 128, 4, 8, 3, 3, 128), (1, 20, 48, 80, 24, 128, 4, 8, 3, 3, 96), (1, 32, 48, 80, 12, 128, 2, 8, 5, 3, 128), (1, 24, 48, 64, 24, 64, 4, 8, 3, 5, 96), (2, 16, 32, 64, 24, 128, 4, 8, 3, 3, 64)]
|
| 37 |
+
CORRECT_SHAPES = [(1, 8, 16, 32, 4, 64, 4, 8, 3, 3, 32), (2, 6, 16, 32, 4, 64, 2, 8, 3, 3, 16), (1, 12, 16, 32, 8, 128, 4, 8, 3, 3, 64), (1, 9, 12, 20, 4, 64, 3, 4, 3, 5, 20), (1, 7, 20, 40, 4, 128, 4, 8, 5, 3, 50), (1, 10, 12, 24, 4, 64, 4, 8, 1, 3, 36)]
|
| 38 |
+
|
| 39 |
+
sys.path.insert(0, "/app")
|
| 40 |
+
|
| 41 |
+
def canonical_work(B, F, Hh, Ww, NH, D, TH, TW, WH, WW, STR):
|
| 42 |
+
"""FLOPs attributed to one forward, from the SHAPE ALONE.
|
| 43 |
+
|
| 44 |
+
Every query sees WH*WW spatial tiles of TS = TH*TW tokens inside its own frame (the window is clamped
|
| 45 |
+
inward, never truncated) plus (F-1)*S/STR strided keys drawn from the OTHER frames -- the two sets are
|
| 46 |
+
disjoint by construction. Each pair costs 4*D FLOPs.
|
| 47 |
+
"""
|
| 48 |
+
TS = TH * TW
|
| 49 |
+
S = Hh * Ww
|
| 50 |
+
keys = WH * WW * TS + (F - 1) * (S // STR)
|
| 51 |
+
return 4 * D * B * NH * (F * S) * keys
|
| 52 |
+
|
| 53 |
+
def _ref(q, k, v, latent, tile, window, stride, scale=None):
|
| 54 |
+
"""In-frame tile window + strided sample of the other frames, as an explicit gather in fp32.
|
| 55 |
+
|
| 56 |
+
Correct and simple — it is the numerical SPECIFICATION, not a performance target. It gathers the whole
|
| 57 |
+
window of every query tile and the whole global set of every query frame and softmaxes them densely.
|
| 58 |
+
"""
|
| 59 |
+
B, T, NH, D = q.shape
|
| 60 |
+
F, Hh, Ww = latent
|
| 61 |
+
th, tw = tile
|
| 62 |
+
wh, ww = window
|
| 63 |
+
nsh, nsw = Hh // th, Ww // tw
|
| 64 |
+
nsp = nsh * nsw
|
| 65 |
+
TS = th * tw
|
| 66 |
+
NW = wh * ww
|
| 67 |
+
S = Hh * Ww
|
| 68 |
+
if scale is None:
|
| 69 |
+
scale = D ** -0.5
|
| 70 |
+
dev = q.device
|
| 71 |
+
|
| 72 |
+
def to_tiles(x):
|
| 73 |
+
return (x.view(B, F, nsh, th, nsw, tw, NH, D)
|
| 74 |
+
.permute(0, 1, 2, 4, 3, 5, 6, 7)
|
| 75 |
+
.reshape(B, F, nsp, TS, NH, D))
|
| 76 |
+
|
| 77 |
+
qt, kt, vt = to_tiles(q.float()), to_tiles(k.float()), to_tiles(v.float())
|
| 78 |
+
kf, vf = k.float(), v.float()
|
| 79 |
+
ot = torch.empty(B, F, nsp, TS, NH, D, device=dev, dtype=torch.float32)
|
| 80 |
+
|
| 81 |
+
sp = torch.arange(nsp, device=dev)
|
| 82 |
+
sh = (sp // nsw - wh // 2).clamp(0, nsh - wh)
|
| 83 |
+
sw = (sp % nsw - ww // 2).clamp(0, nsw - ww)
|
| 84 |
+
ih = sh[:, None] + torch.arange(wh, device=dev)
|
| 85 |
+
iw = sw[:, None] + torch.arange(ww, device=dev)
|
| 86 |
+
wt = (ih[:, :, None] * nsw + iw[:, None, :]).reshape(nsp, NW) # (nsp, wh*ww) tile ids
|
| 87 |
+
|
| 88 |
+
off = torch.arange(0, S, stride, device=dev) # sampled offsets inside a frame
|
| 89 |
+
step = max(1, int(4e8) // max(1, (NW * TS + (F - 1) * off.numel()) * NH * D * 4))
|
| 90 |
+
for f in range(F):
|
| 91 |
+
other = torch.tensor([x for x in range(F) if x != f], device=dev, dtype=torch.long)
|
| 92 |
+
gidx = (other[:, None] * S + off[None, :]).reshape(-1) # global keys of this query frame
|
| 93 |
+
kg, vg = kf[:, gidx], vf[:, gidx] # (B, NG, NH, D)
|
| 94 |
+
for s0 in range(0, nsp, step):
|
| 95 |
+
e0 = min(nsp, s0 + step)
|
| 96 |
+
g = wt[s0:e0]
|
| 97 |
+
kc = torch.cat([kt[:, f][:, g].reshape(B, e0 - s0, NW * TS, NH, D),
|
| 98 |
+
kg.unsqueeze(1).expand(B, e0 - s0, gidx.numel(), NH, D)], dim=2)
|
| 99 |
+
vc = torch.cat([vt[:, f][:, g].reshape(B, e0 - s0, NW * TS, NH, D),
|
| 100 |
+
vg.unsqueeze(1).expand(B, e0 - s0, gidx.numel(), NH, D)], dim=2)
|
| 101 |
+
qc = qt[:, f, s0:e0] * scale
|
| 102 |
+
s = torch.einsum("bcqhd,bckhd->bchqk", qc, kc)
|
| 103 |
+
ot[:, f, s0:e0] = torch.einsum("bchqk,bckhd->bcqhd", torch.softmax(s, dim=-1), vc)
|
| 104 |
+
|
| 105 |
+
return (ot.reshape(B, F, nsh, nsw, th, tw, NH, D)
|
| 106 |
+
.permute(0, 1, 2, 4, 3, 5, 6, 7).reshape(B, T, NH, D))
|
| 107 |
+
|
| 108 |
+
def _mk(B, F, Hh, Ww, NH, D, TH, TW, WH, WW, STR, seed):
|
| 109 |
+
gen = torch.Generator(device="cuda").manual_seed(seed)
|
| 110 |
+
T = F * Hh * Ww
|
| 111 |
+
def r():
|
| 112 |
+
return torch.randn(B, T, NH, D, device="cuda", dtype=torch.bfloat16, generator=gen)
|
| 113 |
+
return r(), r(), r(), (F, Hh, Ww), (TH, TW), (WH, WW), STR
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def _is_exact(t):
|
| 117 |
+
"""Integer/bool tensors are compared EXACTLY: .float() is lossy above 2**24, so two distinct large
|
| 118 |
+
ids (page ids, token ids, indices) can compare equal and let a wrong kernel pass."""
|
| 119 |
+
return t.dtype in (torch.int8, torch.int16, torch.int32, torch.int64, torch.uint8, torch.bool)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def _check(out, ref):
|
| 123 |
+
"""-> (ok, value, msg). Exact for integer/bool; relative Frobenius error otherwise."""
|
| 124 |
+
if out is None or tuple(out.shape) != tuple(ref.shape):
|
| 125 |
+
return False, 1.0, "bad/None shape"
|
| 126 |
+
if _is_exact(ref):
|
| 127 |
+
bad = int((out != ref).sum())
|
| 128 |
+
return bad == 0, float(bad), ("exact match" if bad == 0 else f"{bad} elements differ")
|
| 129 |
+
e = float((out.float() - ref.float()).norm() / (ref.float().norm() + 1e-12))
|
| 130 |
+
return e <= TOL, e, f"relerr {e:.2e}"
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def _bench_fresh(fn, mkargs, reps=5, warm=3):
|
| 134 |
+
"""Time `fn` on FRESH inputs every rep -> (min_seconds, timed_ok). See the module docstring."""
|
| 135 |
+
wargs = mkargs(0)
|
| 136 |
+
for _ in range(warm):
|
| 137 |
+
fn(*wargs)
|
| 138 |
+
torch.cuda.synchronize()
|
| 139 |
+
del wargs
|
| 140 |
+
torch.cuda.empty_cache()
|
| 141 |
+
|
| 142 |
+
best, timed_ok = float("inf"), True
|
| 143 |
+
for i in range(reps):
|
| 144 |
+
args = mkargs(10_000 + i)
|
| 145 |
+
s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
|
| 146 |
+
s.record()
|
| 147 |
+
out = fn(*args)
|
| 148 |
+
e.record()
|
| 149 |
+
torch.cuda.synchronize()
|
| 150 |
+
best = min(best, s.elapsed_time(e))
|
| 151 |
+
if i == reps - 1:
|
| 152 |
+
timed_ok = _check(out, _ref(*args))[0]
|
| 153 |
+
del args, out
|
| 154 |
+
torch.cuda.empty_cache()
|
| 155 |
+
return best / 1e3, timed_ok
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def _geomean(xs):
|
| 159 |
+
return math.exp(sum(math.log(max(v, 1e-9)) for v in xs) / len(xs)) if xs else 0.0
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def main():
|
| 163 |
+
details, correct_gate, geo = {}, False, 0.0
|
| 164 |
+
try:
|
| 165 |
+
spec = importlib.util.spec_from_file_location("submission", MODULE_PATH)
|
| 166 |
+
m = importlib.util.module_from_spec(spec)
|
| 167 |
+
spec.loader.exec_module(m)
|
| 168 |
+
fn = m.window_global_stride_attention
|
| 169 |
+
|
| 170 |
+
corr_ok, msg = True, ""
|
| 171 |
+
for i, shp in enumerate(CORRECT_SHAPES):
|
| 172 |
+
args = _mk(*shp, seed=10 + i)
|
| 173 |
+
ok, val, m_ = _check(fn(*args), _ref(*args))
|
| 174 |
+
if not ok:
|
| 175 |
+
corr_ok, msg = False, f"cfg{i} {shp} {m_}"
|
| 176 |
+
break
|
| 177 |
+
del args
|
| 178 |
+
torch.cuda.empty_cache()
|
| 179 |
+
details["correct_msg"] = msg or "all correctness shapes pass"
|
| 180 |
+
|
| 181 |
+
vals, per_shape, perf_ok = [], [], corr_ok
|
| 182 |
+
for i, shp in enumerate(GRADER_SHAPES):
|
| 183 |
+
args = _mk(*shp, seed=100 + i)
|
| 184 |
+
ok, val, m_ = _check(fn(*args), _ref(*args))
|
| 185 |
+
if not ok:
|
| 186 |
+
perf_ok = False
|
| 187 |
+
del args
|
| 188 |
+
torch.cuda.empty_cache()
|
| 189 |
+
t, timed_ok = _bench_fresh(fn, lambda s, _p=shp: _mk(*_p, seed=s))
|
| 190 |
+
if not timed_ok:
|
| 191 |
+
perf_ok = False
|
| 192 |
+
v = canonical_work(*shp) / t / 1e12 if t > 0 else 0.0
|
| 193 |
+
vals.append(v)
|
| 194 |
+
per_shape.append({"shape": list(shp), "tflops": round(v, 3), "ms": round(t * 1e3, 3),
|
| 195 |
+
"check": m_, "timed_ok": timed_ok})
|
| 196 |
+
geo = _geomean(vals)
|
| 197 |
+
details.update(per_shape=per_shape, geomean=round(geo, 4), perf_size_ok=perf_ok)
|
| 198 |
+
correct_gate = corr_ok and perf_ok
|
| 199 |
+
except Exception as e:
|
| 200 |
+
details["error"] = f"{e.__class__.__name__}: {e}"[:220]
|
| 201 |
+
details["trace"] = traceback.format_exc()[-800:]
|
| 202 |
+
|
| 203 |
+
reward = round(geo, 4) if correct_gate else 0.0
|
| 204 |
+
os.makedirs(REWARD_DIR, exist_ok=True)
|
| 205 |
+
json.dump({"reward": reward, "correct": 1.0 if correct_gate else 0.0,
|
| 206 |
+
"geomean": round(geo, 4), "metric": "TFLOP/s (geomean over graded shapes)"},
|
| 207 |
+
open(f"{REWARD_DIR}/reward.json", "w"), indent=2)
|
| 208 |
+
open(f"{REWARD_DIR}/reward.txt", "w").write(str(reward))
|
| 209 |
+
json.dump(details, open(f"{REWARD_DIR}/details.json", "w"), indent=2, default=str)
|
| 210 |
+
print("reward:", reward, "TFLOP/s | correct:", 1.0 if correct_gate else 0.0)
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
main()
|
tasks/video-sparse-attention/sta-backward/RUN.md
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Running `sta-backward`
|
| 2 |
+
|
| 3 |
+
Fine-tuning a video diffusion transformer on a sparse attention pattern needs the pattern's BACKWARD pass, and that is where the 3D tile window stops being convenient: dQ follows the window, but dK and dV have to accumulate from every query tile whose window covers them, and at the boundary the window is shifted inward so the two directions are NOT mirror images. Recompute the scores, never store the (T, T) probabilities, and get the scatter side right.
|
| 4 |
+
|
| 5 |
+
| | |
|
| 6 |
+
|---|---|
|
| 7 |
+
| **Task id** | `mle-bench/sta-backward` |
|
| 8 |
+
| **Group** | `kernel-generation` |
|
| 9 |
+
| **GPUs** | 1 |
|
| 10 |
+
| **Agent edits** | `/app/sta_bwd.py` |
|
| 11 |
+
| **Score** | achieved **TFLOP/s** (uncapped speed leaderboard), `0` if incorrect |
|
| 12 |
+
| **Grade output** | `tests/test.sh` -> `/logs/verifier/reward.json` |
|
| 13 |
+
|
| 14 |
+
## Run through harbor
|
| 15 |
+
|
| 16 |
+
```bash
|
| 17 |
+
harbor run --dataset-path kernel-generation/kernels/sta-backward --task-name sta-backward \
|
| 18 |
+
--agent claude-code --model anthropic/claude-opus-4-1 -e docker
|
| 19 |
+
```
|
| 20 |
+
|
| 21 |
+
## Run manually
|
| 22 |
+
|
| 23 |
+
```bash
|
| 24 |
+
cd kernel-generation/kernels/sta-backward
|
| 25 |
+
docker build -t sta-backward environment/
|
| 26 |
+
docker run -d --name v --gpus '"device=0"' --shm-size=8g --entrypoint sleep sta-backward infinity
|
| 27 |
+
docker cp tests v:/tests && docker exec v bash /tests/test.sh # untouched start -> reward 0.0
|
| 28 |
+
docker rm -f v
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
Use an **idle** GPU: the score is a timing measurement.
|
| 32 |
+
|
| 33 |
+
## Design
|
| 34 |
+
|
| 35 |
+
Correctness is a hard gate; the score is an absolute hardware metric (TFLOP/s), so the task is
|
| 36 |
+
hardware-portable and needs no gold solution, no oracle, and nothing vendored or sealed.
|
| 37 |
+
|
| 38 |
+
Anti-cheat is structural: the image holds only the permitted toolchain and has no internet; the grader is
|
| 39 |
+
copied in at grade time with its own private copy of the reference; and every timed rep runs on fresh inputs
|
| 40 |
+
with the timed output itself validated, so memoize-and-replay fails the gate.
|
| 41 |
+
|
| 42 |
+
Generated by `_factory/build.py` — edit the spec and regenerate rather than editing this task by hand.
|
tasks/video-sparse-attention/sta-backward/environment/CLAUDE.md
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Working in this environment
|
| 2 |
+
|
| 3 |
+
## ⚠️ Stop background processes without killing yourself
|
| 4 |
+
|
| 5 |
+
You are launched as `claude --print -- '<the task instruction>'`, so the task text — including the
|
| 6 |
+
file names and commands it mentions — is on **your own** process's command line. Any command that
|
| 7 |
+
finds processes by **matching that text** (`pkill -f …`, `pgrep -f … | xargs kill`, a `/proc`
|
| 8 |
+
cmdline scan, `fuser -k`, `killall`) can match and **kill the agent itself**, ending your run
|
| 9 |
+
(`NonZeroAgentExitCodeError`) and grading you on unfinished work.
|
| 10 |
+
|
| 11 |
+
This bites whenever you background something and later stop/restart it — a **server**, a long
|
| 12 |
+
**build** or **training run**, or an **ncu / nsys profiling** session.
|
| 13 |
+
|
| 14 |
+
**Always** manage a background process by its **exact recorded PID**, never by a name pattern:
|
| 15 |
+
|
| 16 |
+
```bash
|
| 17 |
+
nohup <your command> > /tmp/job.log 2>&1 & echo $! > /tmp/job.pid # start + record the PID
|
| 18 |
+
kill "$(cat /tmp/job.pid)"; sleep 3 # stop (SIGTERM); -9 only if needed
|
| 19 |
+
```
|
| 20 |
+
|
| 21 |
+
Use `setsid` and kill the process **group** (`kill -- -"$(cat /tmp/job.pid)"`) if it spawns children.
|
| 22 |
+
If you must enumerate processes, match a **unique token that is NOT anywhere in this prompt** and
|
| 23 |
+
**exclude any cmdline containing `claude` or `--print`** — `pgrep -af`, and look before you kill.
|
| 24 |
+
|
| 25 |
+
Full details + safe recipes: **`/app/PROCESS_MANAGEMENT.md`**.
|
tasks/video-sparse-attention/sta-backward/environment/Dockerfile
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Kernel-generation task: Write a fast Sliding Tile Attention backward kernel
|
| 2 |
+
#
|
| 3 |
+
# Fine-tuning a video diffusion transformer on a sparse attention pattern needs the pattern's BACKWARD pass, and that is where the 3D tile window stops being convenient: dQ follows the window, but dK and dV have to accumulate from every query tile whose window covers them, and at the boundary the window is shifted inward so the two directions are NOT mirror images. Recompute the scores, never store the (T, T) probabilities, and get the scatter side right.
|
| 4 |
+
#
|
| 5 |
+
# SCORING: correctness is a hard gate; the score is achieved TFLOP/s (uncapped leaderboard, 0 if wrong).
|
| 6 |
+
# There is no gold solution and no oracle, so nothing has to be vendored or sealed.
|
| 7 |
+
#
|
| 8 |
+
# TOOLCHAIN POLICY: the agent writes the kernel with Triton (+Gluon), CUDA C++ via nvcc, CUTLASS headers, or
|
| 9 |
+
# the CuTe DSL. Enforcement is by ABSENCE, not by scanning: only the permitted toolchain is installed and
|
| 10 |
+
# there is no internet, so nothing else can be obtained.
|
| 11 |
+
#
|
| 12 |
+
# GENERATED by _factory/build.py.
|
| 13 |
+
FROM pytorch/pytorch:2.11.0-cuda12.8-cudnn9-devel
|
| 14 |
+
|
| 15 |
+
# NOTE: every heavy layer comes FIRST and depends only on {base_image, pip_extra}, so all tasks in this
|
| 16 |
+
# lane share the same cached layers. The task-specific COPYs are LAST. Do not reorder.
|
| 17 |
+
RUN pip install --break-system-packages --no-cache-dir einops nvidia-cutlass-dsl && \
|
| 18 |
+
apt-get update && apt-get install -y --no-install-recommends iptables iproute2 curl ca-certificates build-essential git && \
|
| 19 |
+
curl -LsSf https://astral.sh/uv/install.sh | sh && \
|
| 20 |
+
/root/.local/bin/uv tool install mini-swe-agent
|
| 21 |
+
# header-only CUTLASS for the agent's CUDA/CuTe route
|
| 22 |
+
RUN git clone --depth 1 https://github.com/NVIDIA/cutlass /opt/cutlass && rm -rf /opt/cutlass/.git
|
| 23 |
+
# pre-bake Claude Code; harbor's claude_code.install() skips when present
|
| 24 |
+
RUN curl -fsSL https://deb.nodesource.com/setup_22.x | bash - && \
|
| 25 |
+
apt-get install -y nodejs procps && \
|
| 26 |
+
npm install -g @anthropic-ai/claude-code && claude --version
|
| 27 |
+
ENV PATH=/root/.local/bin:$PATH
|
| 28 |
+
ENV DISABLE_TELEMETRY=1 DISABLE_AUTOUPDATER=1 DISABLE_ERROR_REPORTING=1 CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1
|
| 29 |
+
|
| 30 |
+
COPY restrict-network.sh /app/restrict-network.sh
|
| 31 |
+
RUN chmod +x /app/restrict-network.sh
|
| 32 |
+
# strip apt sources LAST so harbor's post-firewall apt step is a no-op that succeeds
|
| 33 |
+
RUN rm -rf /var/lib/apt/lists/* /etc/apt/sources.list /etc/apt/sources.list.d
|
| 34 |
+
|
| 35 |
+
WORKDIR /app
|
| 36 |
+
COPY CLAUDE.md PROCESS_MANAGEMENT.md /app/
|
| 37 |
+
|
| 38 |
+
# task-specific files LAST so the layers above stay shared across every task
|
| 39 |
+
COPY reference.py /app/reference.py
|
| 40 |
+
COPY measure.py /app/measure.py
|
| 41 |
+
COPY sta_bwd.py /app/sta_bwd.py
|
tasks/video-sparse-attention/sta-backward/environment/PROCESS_MANAGEMENT.md
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Managing background processes — READ THIS before you `kill` anything
|
| 2 |
+
|
| 3 |
+
You may start and stop background processes while iterating — a **server**, a long **build** or
|
| 4 |
+
**training run**, or an **ncu / nsys profiling** session. **The way you stop one can silently kill
|
| 5 |
+
*your own agent process* and end the whole run.** This has happened repeatedly, including via a
|
| 6 |
+
hand-rolled `/proc` scan — not just `pkill`. Read this once and follow the safe recipe.
|
| 7 |
+
|
| 8 |
+
## The trap: matching task text against process command lines
|
| 9 |
+
|
| 10 |
+
You were launched as roughly:
|
| 11 |
+
|
| 12 |
+
```
|
| 13 |
+
claude --print -- '<the entire task instruction text>'
|
| 14 |
+
```
|
| 15 |
+
|
| 16 |
+
The full task instruction is on **your own** process's command line, and it contains the file names
|
| 17 |
+
and commands the task mentions (e.g. `server.py`, `build.sh`, `train.py`, `solution.cu`, `/app/...`).
|
| 18 |
+
So **any** command that finds processes by matching those strings will match — and can kill — **the
|
| 19 |
+
agent itself**:
|
| 20 |
+
|
| 21 |
+
```
|
| 22 |
+
pkill -9 -f "train.py" # matches the claude agent -> kills YOU
|
| 23 |
+
pgrep -f "server.py" | xargs kill # same: the pid list includes claude
|
| 24 |
+
for p in $(pgrep -f build.sh); do kill -9 $p; done # same
|
| 25 |
+
for pid in /proc/*; do case "$(cmdline)" in *solution*) kill -9 $pid;; esac; done # same
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
It is **not about `pkill`** — it is about **matching a string that appears in your prompt**. `pgrep`,
|
| 29 |
+
a `/proc` scan, `fuser`, or `nvidia-smi`-pid loops all have the same failure if the match pattern (or
|
| 30 |
+
the surviving pid list) includes the `claude` process. When you `kill -9` yourself the run dies
|
| 31 |
+
immediately (`NonZeroAgentExitCodeError`) and you are graded on whatever was already in place — usually
|
| 32 |
+
worse than what you were about to finish.
|
| 33 |
+
|
| 34 |
+
## The one safe rule: kill only the exact PID you recorded
|
| 35 |
+
|
| 36 |
+
**Start** a background job and record its PID in a file:
|
| 37 |
+
|
| 38 |
+
```bash
|
| 39 |
+
nohup <your command> > /tmp/job.log 2>&1 &
|
| 40 |
+
echo $! > /tmp/job.pid
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
**Stop / restart** by that exact PID — never by a name pattern:
|
| 44 |
+
|
| 45 |
+
```bash
|
| 46 |
+
kill "$(cat /tmp/job.pid)" 2>/dev/null # SIGTERM: lets it release the GPU / flush cleanly
|
| 47 |
+
sleep 3
|
| 48 |
+
kill -9 "$(cat /tmp/job.pid)" 2>/dev/null # force only if it did not exit
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
If the job spawns workers, run it in its own process group and signal the group by its (negative)
|
| 52 |
+
PGID — still an exact id, never a pattern:
|
| 53 |
+
|
| 54 |
+
```bash
|
| 55 |
+
setsid <your command> > /tmp/job.log 2>&1 < /dev/null & echo $! > /tmp/job.pid
|
| 56 |
+
kill -TERM -- "-$(cat /tmp/job.pid)" 2>/dev/null
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
## If you ever enumerate processes, EXCLUDE the agent
|
| 60 |
+
|
| 61 |
+
Prefer not to. But if you must scan (e.g. hunting a leaked worker), **exclude the `claude` agent and
|
| 62 |
+
your own shell**, and match on a **unique token that is NOT anywhere in this prompt** — give your job
|
| 63 |
+
a unique name and match only that:
|
| 64 |
+
|
| 65 |
+
```bash
|
| 66 |
+
# job named e.g. job_7x3q9 — a token that appears NOWHERE in the task text
|
| 67 |
+
pgrep -af job_7x3q9 | grep -v -E 'claude|--print|pgrep|grep|bash' # LOOK FIRST
|
| 68 |
+
# only kill pids from THIS filtered list, and never a pid whose cmdline contains 'claude' or '--print'
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
Do **not** add a prompt word (a file name, `/app`, `python3`, …) to the pattern "just in case" — that
|
| 72 |
+
single addition re-introduces the self-kill. Match the unique token **only**.
|
| 73 |
+
|
| 74 |
+
## Freeing the GPU without going nuclear
|
| 75 |
+
|
| 76 |
+
If VRAM stays high after you stop a GPU job, the usual cause is a **child process** or a not-yet-
|
| 77 |
+
collected CUDA context — not a stray process you need to hunt across `/proc`. Do this instead of a
|
| 78 |
+
`/proc` sweep:
|
| 79 |
+
|
| 80 |
+
- Kill the job **by its recorded PID / PGID** (above) and `sleep 5–10`; the CUDA context frees after
|
| 81 |
+
the process fully exits.
|
| 82 |
+
- Make the job release cleanly on `SIGTERM` (drop the model / `torch.cuda.empty_cache()` / exit) so a
|
| 83 |
+
single `kill $PID` is enough.
|
| 84 |
+
- Start it in its own group (`setsid`) so `kill -- -$PGID` takes the workers with it.
|
| 85 |
+
- Check with `nvidia-smi` — if a PID still holds memory, `kill` **that exact numeric PID**, after
|
| 86 |
+
confirming its cmdline is **not** `claude` / `--print`.
|
| 87 |
+
|
| 88 |
+
## Rules of thumb
|
| 89 |
+
|
| 90 |
+
- **Never** match a task-prompt string (`server.py`, `train.py`, `build.sh`, `/app`, `python3`, …)
|
| 91 |
+
with `pkill -f`, `pgrep -f`, `killall`, `fuser`, or a `/proc` cmdline scan — they all can hit the
|
| 92 |
+
agent (its argv holds the prompt).
|
| 93 |
+
- **Always** kill a background job by the exact PID from its pidfile (or its PGID).
|
| 94 |
+
- If you must enumerate, match a **unique token not in the prompt** and **exclude `claude` / `--print`
|
| 95 |
+
and your own shell**; `pgrep -af` and look before you kill.
|
| 96 |
+
- `SIGTERM` first for a clean release; `-9` only as a last resort on a specific numeric PID.
|
tasks/video-sparse-attention/sta-backward/environment/docker-compose.yaml
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Anti-cheat firewall overlay, merged on top of Harbor's base compose. Gives the main container
|
| 2 |
+
# NET_ADMIN and runs restrict-network.sh as the entrypoint, so only DNS + the LLM API endpoints are
|
| 3 |
+
# reachable (pypi/github/HF blocked). network_mode stays "public" (see task.toml) — the firewall, not
|
| 4 |
+
# Docker, enforces the allowlist. mini-swe-agent is pre-installed and harbor's patched installer skips
|
| 5 |
+
# the (now-blocked) network install when it is already present.
|
| 6 |
+
services:
|
| 7 |
+
main:
|
| 8 |
+
cap_add:
|
| 9 |
+
- NET_ADMIN
|
| 10 |
+
entrypoint: ["/bin/bash", "/app/restrict-network.sh"]
|
| 11 |
+
environment:
|
| 12 |
+
- ALLOWED_HOSTS=${ALLOWED_HOSTS:-}
|
| 13 |
+
- FIREWORKS_BASE_URL=${FIREWORKS_BASE_URL:-}
|
| 14 |
+
- OPENROUTER_BASE_URL=${OPENROUTER_BASE_URL:-}
|
| 15 |
+
- OPENAI_BASE_URL=${OPENAI_BASE_URL:-}
|
| 16 |
+
- ANTHROPIC_BASE_URL=${ANTHROPIC_BASE_URL:-}
|
| 17 |
+
- LLM_BASE_URL=${LLM_BASE_URL:-}
|
| 18 |
+
- LITELLM_BASE_URL=${LITELLM_BASE_URL:-}
|
tasks/video-sparse-attention/sta-backward/environment/measure.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Self-assessment tool — your correctness + achieved TFLOP/s across a RANGE of shapes.
|
| 2 |
+
|
| 3 |
+
python /app/measure.py # the graded regime
|
| 4 |
+
python /app/measure.py --quick # smaller sizes for fast iteration
|
| 5 |
+
|
| 6 |
+
You are scored on the **geomean achieved TFLOP/s** — NOT one fixed size, and the leaderboard is UNCAPPED
|
| 7 |
+
(higher is always better). The shapes below are a DIFFERENT sample from the same regime the grader uses, so
|
| 8 |
+
optimize for GENERALITY. Work is counted with the same shape-only formula the grader uses, so the number
|
| 9 |
+
printed here is computed exactly as your score is.
|
| 10 |
+
|
| 11 |
+
GENERATED by _factory/build.py.
|
| 12 |
+
"""
|
| 13 |
+
import argparse
|
| 14 |
+
import math
|
| 15 |
+
import sys
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
|
| 19 |
+
sys.path.insert(0, "/app")
|
| 20 |
+
from reference import sta_backward as _ref
|
| 21 |
+
from sta_bwd import sta_backward as _agent
|
| 22 |
+
|
| 23 |
+
TOL = 0.005
|
| 24 |
+
NAMES = ('dq', 'dk', 'dv')
|
| 25 |
+
|
| 26 |
+
FULL = [(1, 12, 48, 80, 16, 128, 2, 4, 8, 3, 3, 3), (1, 12, 32, 80, 24, 128, 2, 4, 8, 3, 3, 3), (1, 16, 32, 80, 16, 128, 4, 4, 8, 3, 3, 3), (1, 12, 32, 64, 16, 128, 2, 4, 8, 3, 5, 5), (2, 12, 32, 32, 16, 64, 2, 4, 8, 5, 3, 3)]
|
| 27 |
+
QUICK = [(1, 8, 24, 40, 8, 128, 2, 4, 8, 3, 3, 3), (1, 8, 16, 40, 8, 64, 2, 4, 8, 3, 3, 3), (1, 8, 24, 24, 8, 128, 2, 4, 8, 3, 3, 3)]
|
| 28 |
+
|
| 29 |
+
def canonical_work(B, F, Hh, Ww, NH, D, TF, TH, TW, WF, WH, WW):
|
| 30 |
+
"""FLOPs attributed to one backward, from the SHAPE ALONE.
|
| 31 |
+
|
| 32 |
+
Every one of the T = F*Hh*Ww queries has exactly KW = WF*WH*WW*TF*TH*TW visible keys (the window is
|
| 33 |
+
clamped, never truncated). Each (query, key) pair costs 10*D FLOPs: 2*D to recompute the score, 2*D for
|
| 34 |
+
dP = dO.V^T, 2*D for dV += P^T.dO, 2*D for dQ += dS.K and 2*D for dK += dS^T.Q. Nothing depends on the
|
| 35 |
+
data or on how the scatter is realised.
|
| 36 |
+
"""
|
| 37 |
+
return 10 * D * B * NH * (F * Hh * Ww) * (WF * WH * WW * TF * TH * TW)
|
| 38 |
+
|
| 39 |
+
def _mk(B, F, Hh, Ww, NH, D, TF, TH, TW, WF, WH, WW, seed):
|
| 40 |
+
gen = torch.Generator(device="cuda").manual_seed(seed)
|
| 41 |
+
T = F * Hh * Ww
|
| 42 |
+
ntf, nth, ntw = F // TF, Hh // TH, Ww // TW
|
| 43 |
+
NT, TS = ntf * nth * ntw, TF * TH * TW
|
| 44 |
+
def r():
|
| 45 |
+
return torch.randn(B, T, NH, D, device="cuda", dtype=torch.bfloat16, generator=gen)
|
| 46 |
+
q, k, v, do = r(), r(), r(), r()
|
| 47 |
+
scale = D ** -0.5
|
| 48 |
+
|
| 49 |
+
# forward pass, chunked over query tiles, to produce a CONSISTENT (lse, delta) pair
|
| 50 |
+
def to_tiles(x):
|
| 51 |
+
return (x.view(B, ntf, TF, nth, TH, ntw, TW, NH, D)
|
| 52 |
+
.permute(0, 1, 3, 5, 2, 4, 6, 7, 8).reshape(B, NT, TS, NH, D))
|
| 53 |
+
qt, kt, vt, dot = (to_tiles(x.float()) for x in (q, k, v, do))
|
| 54 |
+
dev = q.device
|
| 55 |
+
sa = (torch.arange(ntf, device=dev) - WF // 2).clamp(0, ntf - WF)
|
| 56 |
+
sb = (torch.arange(nth, device=dev) - WH // 2).clamp(0, nth - WH)
|
| 57 |
+
sc = (torch.arange(ntw, device=dev) - WW // 2).clamp(0, ntw - WW)
|
| 58 |
+
ia = sa[:, None] + torch.arange(WF, device=dev)
|
| 59 |
+
ib = sb[:, None] + torch.arange(WH, device=dev)
|
| 60 |
+
ic = sc[:, None] + torch.arange(WW, device=dev)
|
| 61 |
+
tid = (((ia[:, None, None, :, None, None] * nth + ib[None, :, None, None, :, None]) * ntw
|
| 62 |
+
+ ic[None, None, :, None, None, :]).reshape(NT, WF * WH * WW))
|
| 63 |
+
KW = WF * WH * WW * TS
|
| 64 |
+
lset = torch.empty(B, NT, TS, NH, device=dev)
|
| 65 |
+
delt = torch.empty(B, NT, TS, NH, device=dev)
|
| 66 |
+
step = max(1, int(2.5e8) // max(1, KW * NH * D * 4))
|
| 67 |
+
for s in range(0, NT, step):
|
| 68 |
+
e = min(NT, s + step)
|
| 69 |
+
g = tid[s:e]
|
| 70 |
+
kc = kt[:, g].reshape(B, e - s, KW, NH, D)
|
| 71 |
+
vc = vt[:, g].reshape(B, e - s, KW, NH, D)
|
| 72 |
+
sc_ = torch.einsum("bcqhd,bckhd->bchqk", qt[:, s:e] * scale, kc)
|
| 73 |
+
l = torch.logsumexp(sc_, dim=-1) # (B, ch, NH, TS)
|
| 74 |
+
o = torch.einsum("bchqk,bckhd->bcqhd", torch.exp(sc_ - l.unsqueeze(-1)), vc)
|
| 75 |
+
lset[:, s:e] = l.permute(0, 1, 3, 2)
|
| 76 |
+
delt[:, s:e] = (o * dot[:, s:e]).sum(-1)
|
| 77 |
+
def un_s(x):
|
| 78 |
+
return (x.reshape(B, ntf, nth, ntw, TF, TH, TW, NH)
|
| 79 |
+
.permute(0, 1, 4, 2, 5, 3, 6, 7).reshape(B, T, NH).permute(0, 2, 1).contiguous())
|
| 80 |
+
return q, k, v, do, un_s(lset), un_s(delt), (F, Hh, Ww), (TF, TH, TW), (WF, WH, WW)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _check(out, ref):
|
| 84 |
+
"""-> (ok, value, msg). value = MAX relative error across the returned tuple."""
|
| 85 |
+
if out is None or len(out) != len(NAMES):
|
| 86 |
+
return False, 1.0, f"expected a {len(NAMES)}-tuple {NAMES}"
|
| 87 |
+
per = []
|
| 88 |
+
for n, a, b in zip(NAMES, out, ref):
|
| 89 |
+
if a is None or tuple(a.shape) != tuple(b.shape):
|
| 90 |
+
return False, 1.0, f"{n} bad shape"
|
| 91 |
+
if b.dtype in (torch.int8, torch.int16, torch.int32, torch.int64, torch.uint8, torch.bool):
|
| 92 |
+
# exact: .float() is lossy above 2**24 and would let distinct large ids compare equal
|
| 93 |
+
bad = int((a != b).sum())
|
| 94 |
+
if bad:
|
| 95 |
+
return False, 1.0, f"{n}: {bad} elements differ"
|
| 96 |
+
continue
|
| 97 |
+
per.append((n, float((a.float() - b.float()).norm() / (b.float().norm() + 1e-12))))
|
| 98 |
+
if not per:
|
| 99 |
+
return True, 0.0, "all integer outputs exact"
|
| 100 |
+
wn, wv = max(per, key=lambda x: x[1])
|
| 101 |
+
return wv <= TOL, wv, f"worst {wn} {wv:.2e}"
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def _bench(fn, reps=8, warm=3):
|
| 105 |
+
for _ in range(warm):
|
| 106 |
+
fn()
|
| 107 |
+
torch.cuda.synchronize()
|
| 108 |
+
best = float("inf")
|
| 109 |
+
for _ in range(reps):
|
| 110 |
+
s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
|
| 111 |
+
s.record()
|
| 112 |
+
fn()
|
| 113 |
+
e.record()
|
| 114 |
+
torch.cuda.synchronize()
|
| 115 |
+
best = min(best, s.elapsed_time(e))
|
| 116 |
+
return best / 1e3
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def main():
|
| 120 |
+
ap = argparse.ArgumentParser()
|
| 121 |
+
ap.add_argument("--quick", action="store_true")
|
| 122 |
+
a = ap.parse_args()
|
| 123 |
+
shapes = QUICK if a.quick else FULL
|
| 124 |
+
print(f"geomean over {len(shapes)} shapes ({'quick' if a.quick else 'full'}); the grader uses "
|
| 125 |
+
f"DIFFERENT sizes in the same regime — optimize for generality\n")
|
| 126 |
+
vals, allok = [], True
|
| 127 |
+
for shp in shapes:
|
| 128 |
+
args = _mk(*shp, seed=sum(int(x) for x in shp) % 9973)
|
| 129 |
+
ref = _ref(*args)
|
| 130 |
+
try:
|
| 131 |
+
out = _agent(*args)
|
| 132 |
+
except Exception as ex:
|
| 133 |
+
print(f" {shp}: RAISED {type(ex).__name__}: {str(ex)[:70]}")
|
| 134 |
+
allok = False
|
| 135 |
+
continue
|
| 136 |
+
ok, val, msg = _check(out, ref)
|
| 137 |
+
allok = allok and ok
|
| 138 |
+
t = _bench(lambda: _agent(*args))
|
| 139 |
+
v = canonical_work(*shp) / t / 1e12 if t > 0 else 0.0
|
| 140 |
+
vals.append(v)
|
| 141 |
+
print(f" {str(shp):28s} {t*1e3:9.2f} ms | {v:9.2f} TFLOP/s | {msg} {'ok' if ok else 'FAIL'}")
|
| 142 |
+
del args, ref, out
|
| 143 |
+
torch.cuda.empty_cache()
|
| 144 |
+
geo = math.exp(sum(math.log(max(v, 1e-9)) for v in vals) / len(vals)) if vals else 0.0
|
| 145 |
+
print(f"\n => GEOMEAN {geo:.2f} TFLOP/s "
|
| 146 |
+
f"({'all correct' if allok else 'SOME WRONG — a wrong kernel scores 0, fix correctness first'})")
|
| 147 |
+
print(" This IS your score, and it is uncapped — higher is always better. Keep pushing.")
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
if __name__ == "__main__":
|
| 151 |
+
main()
|
tasks/video-sparse-attention/sta-backward/environment/reference.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Reference implementation — the CORRECTNESS SPEC for `sta_backward`.
|
| 2 |
+
|
| 3 |
+
This is correct but slow. It defines exactly what your kernel must reproduce; its speed has no
|
| 4 |
+
bearing on your score, which is an absolute TFLOP/s number. GENERATED by _factory/build.py.
|
| 5 |
+
"""
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def sta_backward(q, k, v, do, lse, delta, latent, tile, window, scale=None):
|
| 10 |
+
"""STA backward, written as an explicit tile-gather + scatter-add in fp32.
|
| 11 |
+
|
| 12 |
+
Correct and simple — it is the numerical SPECIFICATION, not a performance target. It gathers each query
|
| 13 |
+
tile's whole (wf*wh*ww) neighbourhood of key/value tiles, materialises the probabilities for that
|
| 14 |
+
neighbourhood, and scatter-adds dk/dv back with index_add_. That gather is many times the size of K.
|
| 15 |
+
"""
|
| 16 |
+
B, T, NH, D = q.shape
|
| 17 |
+
F, Hh, Ww = latent
|
| 18 |
+
tf, th, tw = tile
|
| 19 |
+
wf, wh, ww = window
|
| 20 |
+
ntf, nth, ntw = F // tf, Hh // th, Ww // tw
|
| 21 |
+
NT = ntf * nth * ntw
|
| 22 |
+
TS = tf * th * tw
|
| 23 |
+
NW = wf * wh * ww
|
| 24 |
+
KW = NW * TS
|
| 25 |
+
if scale is None:
|
| 26 |
+
scale = D ** -0.5
|
| 27 |
+
dev = q.device
|
| 28 |
+
|
| 29 |
+
def to_tiles(x):
|
| 30 |
+
return (x.view(B, ntf, tf, nth, th, ntw, tw, NH, D)
|
| 31 |
+
.permute(0, 1, 3, 5, 2, 4, 6, 7, 8)
|
| 32 |
+
.reshape(B, NT, TS, NH, D))
|
| 33 |
+
|
| 34 |
+
def to_tiles_s(x): # (B, NH, T) -> (B, NT, TS, NH)
|
| 35 |
+
return (x.permute(0, 2, 1).view(B, ntf, tf, nth, th, ntw, tw, NH)
|
| 36 |
+
.permute(0, 1, 3, 5, 2, 4, 6, 7).reshape(B, NT, TS, NH))
|
| 37 |
+
|
| 38 |
+
qt, kt, vt, dot = (to_tiles(x.float()) for x in (q, k, v, do))
|
| 39 |
+
lt, dt = to_tiles_s(lse), to_tiles_s(delta)
|
| 40 |
+
|
| 41 |
+
sa = (torch.arange(ntf, device=dev) - wf // 2).clamp(0, ntf - wf)
|
| 42 |
+
sb = (torch.arange(nth, device=dev) - wh // 2).clamp(0, nth - wh)
|
| 43 |
+
sc = (torch.arange(ntw, device=dev) - ww // 2).clamp(0, ntw - ww)
|
| 44 |
+
ia = sa[:, None] + torch.arange(wf, device=dev)
|
| 45 |
+
ib = sb[:, None] + torch.arange(wh, device=dev)
|
| 46 |
+
ic = sc[:, None] + torch.arange(ww, device=dev)
|
| 47 |
+
tid = (((ia[:, None, None, :, None, None] * nth + ib[None, :, None, None, :, None]) * ntw
|
| 48 |
+
+ ic[None, None, :, None, None, :]).reshape(NT, NW))
|
| 49 |
+
|
| 50 |
+
dqt = torch.zeros(B, NT, TS, NH, D, device=dev, dtype=torch.float32)
|
| 51 |
+
dkt = torch.zeros(B, NT, TS, NH, D, device=dev, dtype=torch.float32)
|
| 52 |
+
dvt = torch.zeros(B, NT, TS, NH, D, device=dev, dtype=torch.float32)
|
| 53 |
+
|
| 54 |
+
step = max(1, int(2.5e8) // max(1, KW * NH * D * 4))
|
| 55 |
+
for s in range(0, NT, step):
|
| 56 |
+
e = min(NT, s + step)
|
| 57 |
+
ch = e - s
|
| 58 |
+
g = tid[s:e] # (ch, NW)
|
| 59 |
+
kc = kt[:, g].reshape(B, ch, KW, NH, D)
|
| 60 |
+
vc = vt[:, g].reshape(B, ch, KW, NH, D)
|
| 61 |
+
sc_ = torch.einsum("bcqhd,bckhd->bchqk", qt[:, s:e] * scale, kc)
|
| 62 |
+
p = torch.exp(sc_ - lt[:, s:e].permute(0, 1, 3, 2).unsqueeze(-1))
|
| 63 |
+
dp = torch.einsum("bcqhd,bckhd->bchqk", dot[:, s:e], vc)
|
| 64 |
+
ds = p * (dp - dt[:, s:e].permute(0, 1, 3, 2).unsqueeze(-1))
|
| 65 |
+
dqt[:, s:e] = torch.einsum("bchqk,bckhd->bcqhd", ds, kc) * scale
|
| 66 |
+
dkc = torch.einsum("bchqk,bcqhd->bckhd", ds, qt[:, s:e]) * scale
|
| 67 |
+
dvc = torch.einsum("bchqk,bcqhd->bckhd", p, dot[:, s:e])
|
| 68 |
+
flat = g.reshape(-1)
|
| 69 |
+
dkt.index_add_(1, flat, dkc.reshape(B, ch * NW, TS, NH, D))
|
| 70 |
+
dvt.index_add_(1, flat, dvc.reshape(B, ch * NW, TS, NH, D))
|
| 71 |
+
|
| 72 |
+
def un_tile(x):
|
| 73 |
+
return (x.reshape(B, ntf, nth, ntw, tf, th, tw, NH, D)
|
| 74 |
+
.permute(0, 1, 4, 2, 5, 3, 6, 7, 8).reshape(B, T, NH, D))
|
| 75 |
+
|
| 76 |
+
return un_tile(dqt), un_tile(dkt), un_tile(dvt)
|
tasks/video-sparse-attention/sta-backward/environment/restrict-network.sh
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Outbound firewall (anti-cheat): allow ONLY DNS, loopback, docker-internal networks, and the LLM API
|
| 3 |
+
# endpoints the agent needs. Everything else is dropped — in particular pypi, github, and huggingface,
|
| 4 |
+
# so the agent cannot `pip install vllm` / `pip install sglang` / clone the reference moe_align kernel and
|
| 5 |
+
# copy it. torch + triton are already in the image, and mini-swe-agent is pre-installed (harbor's patched
|
| 6 |
+
# installer skips the network install when it is already present), so no package index is needed at run time.
|
| 7 |
+
#
|
| 8 |
+
# Runs as the container ENTRYPOINT before the CMD. iptables rules are network-namespace-wide, so they also
|
| 9 |
+
# apply to the agent's `docker exec` commands. Requires cap_add: NET_ADMIN.
|
| 10 |
+
set -uo pipefail
|
| 11 |
+
|
| 12 |
+
# LLM API endpoints the agent may reach. Extend at launch via ALLOWED_HOSTS=host1,host2 (no scheme).
|
| 13 |
+
API_HOSTS=(
|
| 14 |
+
api.fireworks.ai
|
| 15 |
+
openrouter.ai openrouter.io
|
| 16 |
+
api.openai.com api.anthropic.com generativelanguage.googleapis.com
|
| 17 |
+
api.together.xyz integrate.api.nvidia.com api.moonshot.cn api.kimi.com
|
| 18 |
+
)
|
| 19 |
+
# Auto-allow hosts from any *_BASE_URL / *_ENDPOINT env var (ANTHROPIC_BASE_URL, OPENAI_BASE_URL, …).
|
| 20 |
+
CUSTOM=()
|
| 21 |
+
while IFS='=' read -r n v; do
|
| 22 |
+
case "$n" in
|
| 23 |
+
*_BASE_URL|*_URL|*_ENDPOINT)
|
| 24 |
+
[ -n "$v" ] && CUSTOM+=("$(echo "$v" | sed 's|.*://||; s|[:/].*||')") ;;
|
| 25 |
+
esac
|
| 26 |
+
done < <(env)
|
| 27 |
+
if [ -n "${ALLOWED_HOSTS:-}" ]; then IFS=',' read -ra E <<< "$ALLOWED_HOSTS"; CUSTOM+=("${E[@]}"); fi
|
| 28 |
+
ALL_HOSTS=("${API_HOSTS[@]}" ${CUSTOM[@]+"${CUSTOM[@]}"})
|
| 29 |
+
|
| 30 |
+
if iptables -L OUTPUT -n >/dev/null 2>&1; then
|
| 31 |
+
echo "restrict-network: applying outbound allowlist firewall..."
|
| 32 |
+
iptables -F OUTPUT 2>/dev/null || true
|
| 33 |
+
iptables -A OUTPUT -o lo -j ACCEPT
|
| 34 |
+
iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
|
| 35 |
+
iptables -A OUTPUT -p udp --dport 53 -j ACCEPT
|
| 36 |
+
iptables -A OUTPUT -p tcp --dport 53 -j ACCEPT
|
| 37 |
+
iptables -A OUTPUT -d 10.0.0.0/8 -j ACCEPT
|
| 38 |
+
iptables -A OUTPUT -d 172.16.0.0/12 -j ACCEPT
|
| 39 |
+
iptables -A OUTPUT -d 192.168.0.0/16 -j ACCEPT
|
| 40 |
+
iptables -A OUTPUT -d 127.0.0.11 -j ACCEPT
|
| 41 |
+
for h in "${ALL_HOSTS[@]}"; do
|
| 42 |
+
for ip in $(getent ahosts "$h" 2>/dev/null | awk '{print $1}' | sort -u); do
|
| 43 |
+
iptables -A OUTPUT -d "$ip" -j ACCEPT
|
| 44 |
+
done
|
| 45 |
+
done
|
| 46 |
+
iptables -A OUTPUT -j REJECT --reject-with icmp-admin-prohibited
|
| 47 |
+
echo "restrict-network: outbound locked to DNS + LLM endpoints; pypi/github/HF blocked."
|
| 48 |
+
else
|
| 49 |
+
echo "restrict-network: WARNING — iptables unavailable (need cap_add NET_ADMIN); NOT firewalled." >&2
|
| 50 |
+
fi
|
| 51 |
+
|
| 52 |
+
exec "$@"
|
tasks/video-sparse-attention/sta-backward/environment/sta_bwd.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Your implementation goes here.
|
| 2 |
+
|
| 3 |
+
Replace the body of `sta_backward` with a FAST implementation that reproduces the output of /app/reference.py
|
| 4 |
+
(same signature, same numerics within tolerance) but is much faster — see /app/instruction.md.
|
| 5 |
+
Run `python /app/measure.py` to check your correctness and achieved TFLOP/s.
|
| 6 |
+
|
| 7 |
+
You may add helper modules, Triton kernels, CUDA extensions, caches, etc. — only this function's name,
|
| 8 |
+
signature and returned value are fixed by the contract.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def sta_backward(q, k, v, do, lse, delta, latent, tile, window, scale=None):
|
| 13 |
+
"""Backward pass of Sliding Tile Attention.
|
| 14 |
+
|
| 15 |
+
Args:
|
| 16 |
+
q, k, v: (B, T, NH, D) bfloat16 — the forward pass's inputs, T = F*Hh*Ww tokens in RASTER order.
|
| 17 |
+
do: (B, T, NH, D) bfloat16 — gradient of the loss w.r.t. the forward output o.
|
| 18 |
+
lse: (B, NH, T) float32 — the forward pass's log-sum-exp per query, natural log.
|
| 19 |
+
delta: (B, NH, T) float32 — rowsum(do * o) per query, the usual flash-attention D term.
|
| 20 |
+
latent: (F, Hh, Ww) tuple of int — latent frames / height / width.
|
| 21 |
+
tile: (tf, th, tw) tuple of int — 3D tile size; divides (F, Hh, Ww) exactly.
|
| 22 |
+
window: (wf, wh, ww) tuple of int — window size measured in TILES, all odd.
|
| 23 |
+
scale: float or None — logit scale used in the forward; None means D ** -0.5.
|
| 24 |
+
|
| 25 |
+
Returns:
|
| 26 |
+
(dq, dk, dv), each (B, T, NH, D) bfloat16 or float32 — must match /app/reference.py numerically.
|
| 27 |
+
"""
|
| 28 |
+
raise NotImplementedError("Implement a fast sta_backward in /app/sta_bwd.py")
|
tasks/video-sparse-attention/sta-backward/instruction.md
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Write a fast Sliding Tile Attention backward kernel
|
| 2 |
+
|
| 3 |
+
You are given a **correct but slow** reference at **`/app/reference.py`** — `sta_backward(q, k, v, do, lse, delta, latent, tile, window, scale=None)`. **Read it, run it, profile it.**
|
| 4 |
+
|
| 5 |
+
Write **`/app/sta_bwd.py`** with the **same signature** and the **same numerical output**, but **as fast as you can make it**.
|
| 6 |
+
|
| 7 |
+
```python
|
| 8 |
+
def sta_backward(q, k, v, do, lse, delta, latent, tile, window, scale=None):
|
| 9 |
+
...
|
| 10 |
+
```
|
| 11 |
+
|
| 12 |
+
## The computation (this is the exact spec)
|
| 13 |
+
|
| 14 |
+
This is the backward pass of **Sliding Tile Attention**. The forward pass it differentiates is:
|
| 15 |
+
the sequence is a 3D latent, token `i` is voxel `(f, h, w)` at `i = (f*Hh + h)*Ww + w` (raster order); the
|
| 16 |
+
latent is cut into `(tf, th, tw)` tiles; and the query tile at tile-coordinate `(a, b, c)` attends to the
|
| 17 |
+
`wf x wh x ww` block of key tiles starting at
|
| 18 |
+
|
| 19 |
+
```
|
| 20 |
+
sa = clamp(a - wf//2, 0, ntf - wf), sb = clamp(b - wh//2, 0, nth - wh), sc = clamp(c - ww//2, 0, ntw - ww)
|
| 21 |
+
```
|
| 22 |
+
|
| 23 |
+
with `ntf, nth, ntw = F/tf, Hh/th, Ww/tw`. The window is **shifted inward at the boundary, never truncated**,
|
| 24 |
+
so every query sees exactly `KW = wf*wh*ww*tf*th*tw` keys. Attention is bidirectional; there is no causal
|
| 25 |
+
mask.
|
| 26 |
+
|
| 27 |
+
You are given `lse` and `delta` from that forward pass, so the probabilities are recovered without a second
|
| 28 |
+
softmax. Writing `M(i)` for the set of keys visible to query `i` and `scale` for the logit scale:
|
| 29 |
+
|
| 30 |
+
```
|
| 31 |
+
p_ij = exp( scale * (q_i . k_j) - lse_i ) for j in M(i), and 0 otherwise
|
| 32 |
+
dp_ij = do_i . v_j
|
| 33 |
+
ds_ij = p_ij * ( dp_ij - delta_i ) delta_i = sum_d do[i,d] * o[i,d]
|
| 34 |
+
dq_i = scale * sum_{j in M(i)} ds_ij * k_j
|
| 35 |
+
dk_j = scale * sum_{i : j in M(i)} ds_ij * q_i
|
| 36 |
+
dv_j = sum_{i : j in M(i)} p_ij * do_i
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
The asymmetry is the whole difficulty. `dq` iterates over the window of the query's own tile — the same
|
| 40 |
+
gather the forward does. `dk` and `dv` iterate over the **inverse** relation `{i : j in M(i)}`, and because
|
| 41 |
+
of the inward shift that set is **not** the mirror window: a key tile at the boundary of the volume is
|
| 42 |
+
covered by *more* query tiles than an interior one (up to `wf//2` extra along each shifted axis), while a
|
| 43 |
+
tile just inside the boundary is covered by fewer. Assuming the relation is symmetric gives a `dk`/`dv` that
|
| 44 |
+
is wrong exactly on the faces of the volume — a small fraction of the tensor with a large error, which is
|
| 45 |
+
easy to miss at a small shape and fatal at a real one.
|
| 46 |
+
|
| 47 |
+
`lse` and `delta` are supplied **consistent with `q, k, v`** under exactly this mask, i.e. `lse[b,h,i] =
|
| 48 |
+
log sum_{j in M(i)} exp(scale * q_i . k_j)`. `p` therefore already sums to one over `M(i)` and needs no
|
| 49 |
+
renormalisation.
|
| 50 |
+
|
| 51 |
+
`/app/reference.py` gathers each query tile's whole neighbourhood and `index_add_`s the key-side gradients
|
| 52 |
+
back. That is the exact specification; it is deliberately simple rather than fast.
|
| 53 |
+
|
| 54 |
+
## The contract (fixed — do not change these)
|
| 55 |
+
|
| 56 |
+
| arg | shape | dtype | meaning |
|
| 57 |
+
|-----|-------|-------|---------|
|
| 58 |
+
| `q`, `k`, `v` | `(B, T, NH, D)` | `bfloat16` | forward inputs, raster-ordered over the latent |
|
| 59 |
+
| `do` | `(B, T, NH, D)` | `bfloat16` | gradient w.r.t. the forward output |
|
| 60 |
+
| `lse` | `(B, NH, T)` | `float32` | forward log-sum-exp (natural log), **head-major** layout |
|
| 61 |
+
| `delta` | `(B, NH, T)` | `float32` | `rowsum(do * o)`, same layout as `lse` |
|
| 62 |
+
| `latent` | 3-tuple | `int` | `(F, Hh, Ww)`; `T == F*Hh*Ww` |
|
| 63 |
+
| `tile` | 3-tuple | `int` | `(tf, th, tw)`; divides `(F, Hh, Ww)` exactly |
|
| 64 |
+
| `window` | 3-tuple | `int` | `(wf, wh, ww)` in **tiles**, all odd, each at most the tile count on that axis |
|
| 65 |
+
| `scale` | scalar | `float` or `None` | logit scale; `None` means `D ** -0.5` |
|
| 66 |
+
|
| 67 |
+
**Return** a 3-tuple `(dq, dk, dv)` **in that order**, each `(B, T, NH, D)` in the same raster order as `q`,
|
| 68 |
+
dtype `bfloat16` or `float32`.
|
| 69 |
+
|
| 70 |
+
`latent`, `tile` and `window` are host-side Python `int` tuples, so the geometry is known before launch. All
|
| 71 |
+
tensors are CUDA, contiguous and **read-only**; nothing is updated in place.
|
| 72 |
+
|
| 73 |
+
No GQA, no causality, no dropout, no bias — and note `lse`/`delta` are `(B, NH, T)`, transposed relative to
|
| 74 |
+
the `(B, T, NH, D)` tensors.
|
| 75 |
+
|
| 76 |
+
**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): video
|
| 77 |
+
latents at fine-tuning resolution — `F x Hh x Ww` from `12 x 32 x 48` up to `20 x 48 x 80` (46k-77k tokens),
|
| 78 |
+
`NH` in 16-24, `D` in {64, 128}, `tile` `(2,4,8)` or `(4,4,8)`, `window` `(3,3,3)`, `(3,5,5)` or `(5,3,3)`.
|
| 79 |
+
`B` is 1-2.
|
| 80 |
+
|
| 81 |
+
The work formula credits only the **windowed** pairs at `10*D` FLOPs each, so a kernel that runs a dense
|
| 82 |
+
backward and masks afterwards is credited nothing for the ~98% of pairs it threw away.
|
| 83 |
+
|
| 84 |
+
## How success is decided (runs on GPU)
|
| 85 |
+
|
| 86 |
+
**1. Correctness — a required gate.** **All three** of `dq`, `dk`, `dv` must match the reference (evaluated in fp32) within
|
| 87 |
+
**relative Frobenius error `5e-3`** at every graded shape, including the timed ones. `dk` and `dv` are graded
|
| 88 |
+
just as hard as `dq`, and the boundary tiles are where a wrong inverse-window shows up.
|
| 89 |
+
|
| 90 |
+
The gate is measured. **Noise floor:** the reference's closed-form gather/scatter backward was checked
|
| 91 |
+
against **`torch.autograd` differentiating a dense masked fp32 forward** — an implementation that shares no
|
| 92 |
+
code path with it and does not use `lse` or `delta` at all — and they agree to **`1.2e-6`**. A second
|
| 93 |
+
independent closed-form version that is whole-sequence dense (no tiling, no gather, no `index_add_`, so `dk`
|
| 94 |
+
and `dv` accumulate in a completely different order) agrees to **`1.1e-6`**. So the tiling, the inverse
|
| 95 |
+
window and the scatter contribute nothing measurable. The floor is set by the dtypes a real kernel uses:
|
| 96 |
+
bf16 operands into all four GEMMs and bf16 gradient outputs measures **`2.38e-3`**, and the gate is **2.1x**
|
| 97 |
+
that.
|
| 98 |
+
|
| 99 |
+
**Discrimination:** a dense backward that ignores the window scores **`3.4`**; truncating the window at the
|
| 100 |
+
volume boundary instead of shifting it inward scores **`1.03`**; and omitting the `delta` subtraction —
|
| 101 |
+
`ds = p * dp` — scores **`0.16`**, still 31x above the gate. That last one is the tightest and it is the
|
| 102 |
+
mistake most worth guarding against, which is why the tolerance is not left at a comfortable `2e-2`. A wrong kernel scores **0**, no matter how fast.
|
| 103 |
+
|
| 104 |
+
**2. Performance — this is your score, and it is an UNCAPPED leaderboard.**
|
| 105 |
+
|
| 106 |
+
```
|
| 107 |
+
reward = geomean over graded shapes of ( canonical_work(shape) / your_runtime ) [TFLOP/s]
|
| 108 |
+
reward = 0 if the submission is wrong at any graded shape
|
| 109 |
+
```
|
| 110 |
+
|
| 111 |
+
`canonical_work` depends **only on the shape**, never on how you implemented it, so every submission is
|
| 112 |
+
credited the same work and this is a pure speed ranking in useful units:
|
| 113 |
+
|
| 114 |
+
```
|
| 115 |
+
T = F * Hh * Ww
|
| 116 |
+
KW = WF*WH*WW * TF*TH*TW # keys visible to EVERY query
|
| 117 |
+
FLOPs = 10 * D * B * NH * T * KW # 2*D recompute S, then dP, dV, dQ, dK at 2*D each
|
| 118 |
+
```
|
| 119 |
+
|
| 120 |
+
**There is no cap and no target.** Higher TFLOP/s is always a strictly better score, so **push the
|
| 121 |
+
performance as hard as you can**. Getting a correct implementation is the *start* of the task, not the end of
|
| 122 |
+
it. Once correct, spend the entire remainder of your budget profiling and optimising, re-checking correctness
|
| 123 |
+
after every change. **Use your full time budget.**
|
| 124 |
+
|
| 125 |
+
Run **`python /app/measure.py`** at any point to see your per-shape and geomean TFLOP/s plus correctness.
|
| 126 |
+
|
| 127 |
+
## Where the performance comes from
|
| 128 |
+
|
| 129 |
+
The reference gathers `wf*wh*ww` key/value tiles per query tile, materialises the whole
|
| 130 |
+
probability block, and `index_add_`s the result back — tens of gigabytes of traffic and an atomics storm.
|
| 131 |
+
|
| 132 |
+
**Split the pass in two, as flash-attention does.** One kernel parallel over query tiles produces `dq` by
|
| 133 |
+
walking that tile's window (a pure gather, no atomics). A second kernel parallel over **key** tiles produces
|
| 134 |
+
`dk` and `dv` by walking the *inverse* window — the set of query tiles whose window contains this key tile.
|
| 135 |
+
Both loops are over the same total number of pairs, and neither needs an atomic if you enumerate the inverse
|
| 136 |
+
set correctly.
|
| 137 |
+
|
| 138 |
+
**Enumerate the inverse window in closed form.** Query tile `a` covers key tiles `[sa(a), sa(a)+wf)` with
|
| 139 |
+
`sa(a) = clamp(a - wf//2, 0, ntf - wf)`. Inverting: key tile `a'` is covered by exactly those `a` with
|
| 140 |
+
`sa(a) <= a' < sa(a)+wf`, which is a contiguous range of `a` — of length `wf` in the interior, but *longer*
|
| 141 |
+
at the two ends of the axis because `sa` saturates there. The three axes are independent, so the inverse set
|
| 142 |
+
is again a box of query tiles, just a differently-sized one. Computing that box with two `clamp`s beats
|
| 143 |
+
building an explicit inverse table, and it means the key-side kernel is a clean nested loop with no gather
|
| 144 |
+
list at all.
|
| 145 |
+
|
| 146 |
+
**Do not store P.** Recompute `s = scale * q.k^T` inside both passes and rebuild `p = exp(s - lse)` from the
|
| 147 |
+
supplied `lse`. Storing the probabilities would be `KW` floats per query — larger than every other tensor in
|
| 148 |
+
the problem combined.
|
| 149 |
+
|
| 150 |
+
**Layout.** The tokens of a 3D tile are a strided box in the raster sequence. Either permute `q, k, v, do`
|
| 151 |
+
into tile-major order once (three streaming passes, then every tile load is contiguous) or issue the strided
|
| 152 |
+
loads directly into shared memory. `lse` and `delta` are `(B, NH, T)` — head-major — so their tile gather has
|
| 153 |
+
a different stride pattern from the `(B, T, NH, D)` tensors; loading them once per tile into shared memory
|
| 154 |
+
avoids re-reading them per key tile.
|
| 155 |
+
|
| 156 |
+
**Balance.** Boundary key tiles have a larger inverse set than interior ones (by up to `(wf//2)` query tiles
|
| 157 |
+
per axis), so a static one-threadblock-per-key-tile grid has a genuine tail. With `ntf*nth*ntw` in the
|
| 158 |
+
thousands and `NH` in the tens there is enough parallelism to hide it, but a persistent grid over a flattened
|
| 159 |
+
work list does better.
|
| 160 |
+
|
| 161 |
+
## Precision and faithfulness (read this)
|
| 162 |
+
|
| 163 |
+
`q, k, v, do` are **bfloat16**; `lse` and `delta` are **float32**. Do the matmuls on bf16
|
| 164 |
+
tensor cores with **fp32 accumulation**, and keep `p`, `ds` and all three gradient accumulators in fp32.
|
| 165 |
+
|
| 166 |
+
The tolerance is **`5e-3`**, measured rather than inherited: `torch.autograd` through a dense masked fp32
|
| 167 |
+
forward reproduces the reference to **`1.2e-6`**, and the floor comes from bf16 GEMM operands and bf16
|
| 168 |
+
gradient outputs, which measure **`2.38e-3`**. The gate is 2.1x that.
|
| 169 |
+
|
| 170 |
+
`ds = p * (dp - delta)` is a *difference* of two quantities of similar magnitude, so subtract in **fp32**.
|
| 171 |
+
Measured honestly, this one is less punishing than it sounds at these shapes — rounding `dp` and `delta` to
|
| 172 |
+
bf16 *before* the subtraction costs `1.7e-3`, inside the gate — but it buys nothing (the subtraction is a
|
| 173 |
+
CUDA-core op either way) and the cancellation gets worse as `do` becomes correlated with `o`, which it is in
|
| 174 |
+
real training and is not in this fixture. Keep it in fp32.
|
| 175 |
+
|
| 176 |
+
`dk` and `dv` are **reductions over a large number of query tiles** — up to `wf*wh*ww` plus the boundary
|
| 177 |
+
excess. Accumulate them in fp32 registers or fp32 shared memory. If you do use atomics, use fp32 atomics; a
|
| 178 |
+
bf16 atomic accumulation over that many contributions drifts far past the gate.
|
| 179 |
+
|
| 180 |
+
The window geometry is exact integer bookkeeping. Do not approximate the inverse window by the mirror window
|
| 181 |
+
— that is a systematic error concentrated on the faces of the volume, not a rounding difference.
|
| 182 |
+
|
| 183 |
+
Do **not** infer from the reference that fp32 storage is wanted; it computes in fp32 purely to be a stable
|
| 184 |
+
numerical *specification*.
|
| 185 |
+
|
| 186 |
+
### What the tolerance does NOT permit
|
| 187 |
+
|
| 188 |
+
The tolerance exists **only** to absorb low-precision arithmetic noise. You are responsible for a **faithful
|
| 189 |
+
implementation of the specified computation**. It is not a budget to spend on approximation. The following
|
| 190 |
+
are wrong answers even if they happen to land inside the tolerance at some shape:
|
| 191 |
+
|
| 192 |
+
- changing the algorithm to something that merely *approximates* the spec (dropping terms, truncating a
|
| 193 |
+
series, low-rank or sketched substitutes, skipping a correction term);
|
| 194 |
+
- shortening the computation (fewer iterations/steps than specified, early exit on a heuristic, subsampling
|
| 195 |
+
or striding over the sequence, ignoring positions whose contribution "looks small");
|
| 196 |
+
- computing at a coarser granularity than the spec (sharing a decay, scale, or normaliser across positions
|
| 197 |
+
that the spec gives their own);
|
| 198 |
+
- anything whose error **grows** with sequence length, batch, or head count.
|
| 199 |
+
|
| 200 |
+
A faithful bf16/fp8 kernel's error is *noise*: it stays flat as the problem grows and sits an order of
|
| 201 |
+
magnitude below the gate. An approximation's error is *bias*: it scales with the problem. The graded shapes
|
| 202 |
+
are deliberately large, so the difference shows up.
|
| 203 |
+
|
| 204 |
+
## What's available
|
| 205 |
+
|
| 206 |
+
- **Triton 3.6** (with Gluon), **CUDA C++ via `nvcc`** (`torch.utils.cpp_extension.load` for an inline
|
| 207 |
+
extension), header-only **CUTLASS** at `/opt/cutlass/include`, and the **CuTe DSL**
|
| 208 |
+
(`nvidia-cutlass-dsl`). C++ / CuTe DSL is the encouraged route; Triton is fully supported.
|
| 209 |
+
- `torch` 2.11 (CUDA 12.8) and `einops` for bookkeeping.
|
| 210 |
+
- A GPU with compute capability sm≥90 (Hopper or newer).
|
| 211 |
+
- **No internet access.** `pip install` and cloning repos are blocked. Everything you are permitted to use is
|
| 212 |
+
already installed, and no library implementation of this kernel exists on the machine.
|
| 213 |
+
- Manage any long-running background job (a build, an `ncu`/`nsys` profile) by its **recorded PID** — see
|
| 214 |
+
`/app/CLAUDE.md` and `/app/PROCESS_MANAGEMENT.md`.
|
| 215 |
+
|
| 216 |
+
## How the grading actually runs (so there are no surprises)
|
| 217 |
+
|
| 218 |
+
- **`/app/sta_bwd.py` is the only file that is graded.** The grader imports `sta_backward` from it and reads nothing
|
| 219 |
+
else from `/app`.
|
| 220 |
+
- **The grader is not on this machine while you work.** It is copied in only after your session ends and it
|
| 221 |
+
carries its **own private copy of the reference** and its own input generator. Editing `/app/reference.py`
|
| 222 |
+
or `/app/measure.py` is allowed — they are yours to experiment with — but it has **no effect whatsoever on
|
| 223 |
+
your score**. Do not spend budget on them.
|
| 224 |
+
- **Every timed repetition uses freshly generated inputs**, and the output of a timed call is itself checked
|
| 225 |
+
against the reference. Caching or memoizing a result and replaying it fails the correctness gate rather
|
| 226 |
+
than producing a fast measurement. Ordinary shape-keyed JIT/autotune caching is fine and is not penalised.
|
| 227 |
+
- **The timed shapes are correctness-checked too.** Being correct only at the small shapes scores **0**.
|
| 228 |
+
- Inputs are random each grade and the graded shapes are not the ones in `measure.py`.
|
tasks/video-sparse-attention/sta-backward/task.toml
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
schema_version = "1.1"
|
| 2 |
+
|
| 3 |
+
[task]
|
| 4 |
+
name = "mle-bench/sta-backward"
|
| 5 |
+
description = "Fine-tuning a video diffusion transformer on a sparse attention pattern needs the pattern's BACKWARD pass, and that is where the 3D tile window stops being convenient: dQ follows the window, but dK and dV have to accumulate from every query tile whose window covers them, and at the boundary the window is shifted inward so the two directions are NOT mirror images. Recompute the scores, never store the (T, T) probabilities, and get the scatter side right."
|
| 6 |
+
authors = []
|
| 7 |
+
keywords = ["mle", "kernel-generation", "attention", "backward", "sparse-attention", "video-diffusion", "sliding-tile-attention", "hunyuanvideo", "training"]
|
| 8 |
+
|
| 9 |
+
[metadata]
|
| 10 |
+
suite = "mle-bench"
|
| 11 |
+
group = "kernel-generation"
|
| 12 |
+
level = "1.0"
|
| 13 |
+
difficulty = "hard"
|
| 14 |
+
category = "mle"
|
| 15 |
+
tags = [ "mle", "kernel-generation", "kernels", "gpu", "real-world",]
|
| 16 |
+
|
| 17 |
+
[verifier]
|
| 18 |
+
timeout_sec = 1800.0
|
| 19 |
+
|
| 20 |
+
[agent]
|
| 21 |
+
timeout_sec = 14400.0
|
| 22 |
+
|
| 23 |
+
# GPU request: honored by Modal/GKE/Daytona. On the local docker backend set environment.override_gpus: 0
|
| 24 |
+
# in the job config and attach a GPU via configs/gpu_overlay_nvidia.yaml (see RUNNING.md §5).
|
| 25 |
+
[environment]
|
| 26 |
+
build_timeout_sec = 3600.0
|
| 27 |
+
cpus = 8
|
| 28 |
+
memory_mb = 65536
|
| 29 |
+
storage_mb = 40960
|
| 30 |
+
gpus = 1
|
| 31 |
+
network_mode = "public"
|
| 32 |
+
mcp_servers = []
|
| 33 |
+
|
| 34 |
+
[verifier.env]
|
| 35 |
+
|
| 36 |
+
[environment.env]
|
| 37 |
+
|
| 38 |
+
[solution.env]
|
tasks/video-sparse-attention/sta-backward/tests/test.sh
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# GENERATED by _factory/build.py. python3 (not python): some CUDA bases lack the symlink.
|
| 3 |
+
set -u
|
| 4 |
+
mkdir -p /logs/verifier
|
| 5 |
+
python3 /tests/verify_env.py
|
tasks/video-sparse-attention/sta-backward/tests/verify_env.py
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""sta-backward verifier — correctness gate + achieved-TFLOP/s SPEED LEADERBOARD (uncapped).
|
| 2 |
+
|
| 3 |
+
reward = 0 if the submission is incorrect
|
| 4 |
+
reward = geomean over graded shapes of TFLOP/s otherwise
|
| 5 |
+
|
| 6 |
+
GENERATED by _factory/build.py — do not edit here; edit the spec and regenerate.
|
| 7 |
+
|
| 8 |
+
There is no gold solution and no oracle: the score is an absolute hardware metric, so it is hardware-portable
|
| 9 |
+
by construction and nothing has to be vendored, sealed, or re-benchmarked.
|
| 10 |
+
|
| 11 |
+
CORRECTNESS is a hard gate, checked against an INDEPENDENT (embedded) copy of the reference at every graded
|
| 12 |
+
shape including the timed ones, so editing /app/reference.py cannot affect grading and a fast wrong kernel
|
| 13 |
+
scores 0.
|
| 14 |
+
|
| 15 |
+
ANTI-CHEAT on the timing path: every timed rep runs on FRESHLY generated inputs, and the output of the last
|
| 16 |
+
timed rep is itself validated against the reference for those exact inputs. A submission that memoizes a
|
| 17 |
+
result and replays it fails the gate instead of posting an inflated number. Warm-up runs on a separate
|
| 18 |
+
throwaway input set, so ordinary shape-keyed JIT/autotune caching is not penalised.
|
| 19 |
+
|
| 20 |
+
WORK is attributed by a CANONICAL formula that depends only on the shape, never on the implementation, so all
|
| 21 |
+
submissions are credited identically and the ranking is a pure speed ranking.
|
| 22 |
+
"""
|
| 23 |
+
import importlib.util
|
| 24 |
+
import json
|
| 25 |
+
import math
|
| 26 |
+
import os
|
| 27 |
+
import sys
|
| 28 |
+
import traceback
|
| 29 |
+
|
| 30 |
+
import torch
|
| 31 |
+
|
| 32 |
+
REWARD_DIR = "/logs/verifier"
|
| 33 |
+
MODULE_PATH = "/app/sta_bwd.py"
|
| 34 |
+
TOL = 0.005
|
| 35 |
+
NAMES = ('dq', 'dk', 'dv')
|
| 36 |
+
|
| 37 |
+
GRADER_SHAPES = [(1, 16, 48, 80, 16, 128, 2, 4, 8, 3, 3, 3), (1, 12, 48, 80, 24, 128, 2, 4, 8, 3, 3, 3), (1, 20, 32, 80, 16, 128, 4, 4, 8, 3, 3, 3), (1, 12, 32, 80, 16, 128, 2, 4, 8, 3, 5, 5), (2, 12, 32, 48, 16, 64, 2, 4, 8, 5, 3, 3)]
|
| 38 |
+
CORRECT_SHAPES = [(1, 8, 16, 32, 4, 64, 2, 4, 8, 3, 3, 3), (2, 10, 16, 32, 4, 64, 2, 4, 8, 3, 3, 3), (1, 12, 16, 32, 8, 128, 3, 4, 8, 3, 3, 3), (1, 10, 10, 20, 4, 64, 2, 2, 4, 3, 3, 3), (1, 12, 16, 32, 4, 64, 2, 4, 8, 5, 3, 3), (1, 8, 20, 40, 4, 128, 2, 4, 8, 1, 3, 3)]
|
| 39 |
+
|
| 40 |
+
sys.path.insert(0, "/app")
|
| 41 |
+
|
| 42 |
+
def canonical_work(B, F, Hh, Ww, NH, D, TF, TH, TW, WF, WH, WW):
|
| 43 |
+
"""FLOPs attributed to one backward, from the SHAPE ALONE.
|
| 44 |
+
|
| 45 |
+
Every one of the T = F*Hh*Ww queries has exactly KW = WF*WH*WW*TF*TH*TW visible keys (the window is
|
| 46 |
+
clamped, never truncated). Each (query, key) pair costs 10*D FLOPs: 2*D to recompute the score, 2*D for
|
| 47 |
+
dP = dO.V^T, 2*D for dV += P^T.dO, 2*D for dQ += dS.K and 2*D for dK += dS^T.Q. Nothing depends on the
|
| 48 |
+
data or on how the scatter is realised.
|
| 49 |
+
"""
|
| 50 |
+
return 10 * D * B * NH * (F * Hh * Ww) * (WF * WH * WW * TF * TH * TW)
|
| 51 |
+
|
| 52 |
+
def _ref(q, k, v, do, lse, delta, latent, tile, window, scale=None):
|
| 53 |
+
"""STA backward, written as an explicit tile-gather + scatter-add in fp32.
|
| 54 |
+
|
| 55 |
+
Correct and simple — it is the numerical SPECIFICATION, not a performance target. It gathers each query
|
| 56 |
+
tile's whole (wf*wh*ww) neighbourhood of key/value tiles, materialises the probabilities for that
|
| 57 |
+
neighbourhood, and scatter-adds dk/dv back with index_add_. That gather is many times the size of K.
|
| 58 |
+
"""
|
| 59 |
+
B, T, NH, D = q.shape
|
| 60 |
+
F, Hh, Ww = latent
|
| 61 |
+
tf, th, tw = tile
|
| 62 |
+
wf, wh, ww = window
|
| 63 |
+
ntf, nth, ntw = F // tf, Hh // th, Ww // tw
|
| 64 |
+
NT = ntf * nth * ntw
|
| 65 |
+
TS = tf * th * tw
|
| 66 |
+
NW = wf * wh * ww
|
| 67 |
+
KW = NW * TS
|
| 68 |
+
if scale is None:
|
| 69 |
+
scale = D ** -0.5
|
| 70 |
+
dev = q.device
|
| 71 |
+
|
| 72 |
+
def to_tiles(x):
|
| 73 |
+
return (x.view(B, ntf, tf, nth, th, ntw, tw, NH, D)
|
| 74 |
+
.permute(0, 1, 3, 5, 2, 4, 6, 7, 8)
|
| 75 |
+
.reshape(B, NT, TS, NH, D))
|
| 76 |
+
|
| 77 |
+
def to_tiles_s(x): # (B, NH, T) -> (B, NT, TS, NH)
|
| 78 |
+
return (x.permute(0, 2, 1).view(B, ntf, tf, nth, th, ntw, tw, NH)
|
| 79 |
+
.permute(0, 1, 3, 5, 2, 4, 6, 7).reshape(B, NT, TS, NH))
|
| 80 |
+
|
| 81 |
+
qt, kt, vt, dot = (to_tiles(x.float()) for x in (q, k, v, do))
|
| 82 |
+
lt, dt = to_tiles_s(lse), to_tiles_s(delta)
|
| 83 |
+
|
| 84 |
+
sa = (torch.arange(ntf, device=dev) - wf // 2).clamp(0, ntf - wf)
|
| 85 |
+
sb = (torch.arange(nth, device=dev) - wh // 2).clamp(0, nth - wh)
|
| 86 |
+
sc = (torch.arange(ntw, device=dev) - ww // 2).clamp(0, ntw - ww)
|
| 87 |
+
ia = sa[:, None] + torch.arange(wf, device=dev)
|
| 88 |
+
ib = sb[:, None] + torch.arange(wh, device=dev)
|
| 89 |
+
ic = sc[:, None] + torch.arange(ww, device=dev)
|
| 90 |
+
tid = (((ia[:, None, None, :, None, None] * nth + ib[None, :, None, None, :, None]) * ntw
|
| 91 |
+
+ ic[None, None, :, None, None, :]).reshape(NT, NW))
|
| 92 |
+
|
| 93 |
+
dqt = torch.zeros(B, NT, TS, NH, D, device=dev, dtype=torch.float32)
|
| 94 |
+
dkt = torch.zeros(B, NT, TS, NH, D, device=dev, dtype=torch.float32)
|
| 95 |
+
dvt = torch.zeros(B, NT, TS, NH, D, device=dev, dtype=torch.float32)
|
| 96 |
+
|
| 97 |
+
step = max(1, int(2.5e8) // max(1, KW * NH * D * 4))
|
| 98 |
+
for s in range(0, NT, step):
|
| 99 |
+
e = min(NT, s + step)
|
| 100 |
+
ch = e - s
|
| 101 |
+
g = tid[s:e] # (ch, NW)
|
| 102 |
+
kc = kt[:, g].reshape(B, ch, KW, NH, D)
|
| 103 |
+
vc = vt[:, g].reshape(B, ch, KW, NH, D)
|
| 104 |
+
sc_ = torch.einsum("bcqhd,bckhd->bchqk", qt[:, s:e] * scale, kc)
|
| 105 |
+
p = torch.exp(sc_ - lt[:, s:e].permute(0, 1, 3, 2).unsqueeze(-1))
|
| 106 |
+
dp = torch.einsum("bcqhd,bckhd->bchqk", dot[:, s:e], vc)
|
| 107 |
+
ds = p * (dp - dt[:, s:e].permute(0, 1, 3, 2).unsqueeze(-1))
|
| 108 |
+
dqt[:, s:e] = torch.einsum("bchqk,bckhd->bcqhd", ds, kc) * scale
|
| 109 |
+
dkc = torch.einsum("bchqk,bcqhd->bckhd", ds, qt[:, s:e]) * scale
|
| 110 |
+
dvc = torch.einsum("bchqk,bcqhd->bckhd", p, dot[:, s:e])
|
| 111 |
+
flat = g.reshape(-1)
|
| 112 |
+
dkt.index_add_(1, flat, dkc.reshape(B, ch * NW, TS, NH, D))
|
| 113 |
+
dvt.index_add_(1, flat, dvc.reshape(B, ch * NW, TS, NH, D))
|
| 114 |
+
|
| 115 |
+
def un_tile(x):
|
| 116 |
+
return (x.reshape(B, ntf, nth, ntw, tf, th, tw, NH, D)
|
| 117 |
+
.permute(0, 1, 4, 2, 5, 3, 6, 7, 8).reshape(B, T, NH, D))
|
| 118 |
+
|
| 119 |
+
return un_tile(dqt), un_tile(dkt), un_tile(dvt)
|
| 120 |
+
|
| 121 |
+
def _mk(B, F, Hh, Ww, NH, D, TF, TH, TW, WF, WH, WW, seed):
|
| 122 |
+
gen = torch.Generator(device="cuda").manual_seed(seed)
|
| 123 |
+
T = F * Hh * Ww
|
| 124 |
+
ntf, nth, ntw = F // TF, Hh // TH, Ww // TW
|
| 125 |
+
NT, TS = ntf * nth * ntw, TF * TH * TW
|
| 126 |
+
def r():
|
| 127 |
+
return torch.randn(B, T, NH, D, device="cuda", dtype=torch.bfloat16, generator=gen)
|
| 128 |
+
q, k, v, do = r(), r(), r(), r()
|
| 129 |
+
scale = D ** -0.5
|
| 130 |
+
|
| 131 |
+
# forward pass, chunked over query tiles, to produce a CONSISTENT (lse, delta) pair
|
| 132 |
+
def to_tiles(x):
|
| 133 |
+
return (x.view(B, ntf, TF, nth, TH, ntw, TW, NH, D)
|
| 134 |
+
.permute(0, 1, 3, 5, 2, 4, 6, 7, 8).reshape(B, NT, TS, NH, D))
|
| 135 |
+
qt, kt, vt, dot = (to_tiles(x.float()) for x in (q, k, v, do))
|
| 136 |
+
dev = q.device
|
| 137 |
+
sa = (torch.arange(ntf, device=dev) - WF // 2).clamp(0, ntf - WF)
|
| 138 |
+
sb = (torch.arange(nth, device=dev) - WH // 2).clamp(0, nth - WH)
|
| 139 |
+
sc = (torch.arange(ntw, device=dev) - WW // 2).clamp(0, ntw - WW)
|
| 140 |
+
ia = sa[:, None] + torch.arange(WF, device=dev)
|
| 141 |
+
ib = sb[:, None] + torch.arange(WH, device=dev)
|
| 142 |
+
ic = sc[:, None] + torch.arange(WW, device=dev)
|
| 143 |
+
tid = (((ia[:, None, None, :, None, None] * nth + ib[None, :, None, None, :, None]) * ntw
|
| 144 |
+
+ ic[None, None, :, None, None, :]).reshape(NT, WF * WH * WW))
|
| 145 |
+
KW = WF * WH * WW * TS
|
| 146 |
+
lset = torch.empty(B, NT, TS, NH, device=dev)
|
| 147 |
+
delt = torch.empty(B, NT, TS, NH, device=dev)
|
| 148 |
+
step = max(1, int(2.5e8) // max(1, KW * NH * D * 4))
|
| 149 |
+
for s in range(0, NT, step):
|
| 150 |
+
e = min(NT, s + step)
|
| 151 |
+
g = tid[s:e]
|
| 152 |
+
kc = kt[:, g].reshape(B, e - s, KW, NH, D)
|
| 153 |
+
vc = vt[:, g].reshape(B, e - s, KW, NH, D)
|
| 154 |
+
sc_ = torch.einsum("bcqhd,bckhd->bchqk", qt[:, s:e] * scale, kc)
|
| 155 |
+
l = torch.logsumexp(sc_, dim=-1) # (B, ch, NH, TS)
|
| 156 |
+
o = torch.einsum("bchqk,bckhd->bcqhd", torch.exp(sc_ - l.unsqueeze(-1)), vc)
|
| 157 |
+
lset[:, s:e] = l.permute(0, 1, 3, 2)
|
| 158 |
+
delt[:, s:e] = (o * dot[:, s:e]).sum(-1)
|
| 159 |
+
def un_s(x):
|
| 160 |
+
return (x.reshape(B, ntf, nth, ntw, TF, TH, TW, NH)
|
| 161 |
+
.permute(0, 1, 4, 2, 5, 3, 6, 7).reshape(B, T, NH).permute(0, 2, 1).contiguous())
|
| 162 |
+
return q, k, v, do, un_s(lset), un_s(delt), (F, Hh, Ww), (TF, TH, TW), (WF, WH, WW)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def _check(out, ref):
|
| 166 |
+
"""-> (ok, value, msg). value = MAX relative error across the returned tuple."""
|
| 167 |
+
if out is None or len(out) != len(NAMES):
|
| 168 |
+
return False, 1.0, f"expected a {len(NAMES)}-tuple {NAMES}"
|
| 169 |
+
per = []
|
| 170 |
+
for n, a, b in zip(NAMES, out, ref):
|
| 171 |
+
if a is None or tuple(a.shape) != tuple(b.shape):
|
| 172 |
+
return False, 1.0, f"{n} bad shape"
|
| 173 |
+
if b.dtype in (torch.int8, torch.int16, torch.int32, torch.int64, torch.uint8, torch.bool):
|
| 174 |
+
# exact: .float() is lossy above 2**24 and would let distinct large ids compare equal
|
| 175 |
+
bad = int((a != b).sum())
|
| 176 |
+
if bad:
|
| 177 |
+
return False, 1.0, f"{n}: {bad} elements differ"
|
| 178 |
+
continue
|
| 179 |
+
per.append((n, float((a.float() - b.float()).norm() / (b.float().norm() + 1e-12))))
|
| 180 |
+
if not per:
|
| 181 |
+
return True, 0.0, "all integer outputs exact"
|
| 182 |
+
wn, wv = max(per, key=lambda x: x[1])
|
| 183 |
+
return wv <= TOL, wv, f"worst {wn} {wv:.2e}"
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def _bench_fresh(fn, mkargs, reps=5, warm=3):
|
| 187 |
+
"""Time `fn` on FRESH inputs every rep -> (min_seconds, timed_ok). See the module docstring."""
|
| 188 |
+
wargs = mkargs(0)
|
| 189 |
+
for _ in range(warm):
|
| 190 |
+
fn(*wargs)
|
| 191 |
+
torch.cuda.synchronize()
|
| 192 |
+
del wargs
|
| 193 |
+
torch.cuda.empty_cache()
|
| 194 |
+
|
| 195 |
+
best, timed_ok = float("inf"), True
|
| 196 |
+
for i in range(reps):
|
| 197 |
+
args = mkargs(10_000 + i)
|
| 198 |
+
s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
|
| 199 |
+
s.record()
|
| 200 |
+
out = fn(*args)
|
| 201 |
+
e.record()
|
| 202 |
+
torch.cuda.synchronize()
|
| 203 |
+
best = min(best, s.elapsed_time(e))
|
| 204 |
+
if i == reps - 1:
|
| 205 |
+
timed_ok = _check(out, _ref(*args))[0]
|
| 206 |
+
del args, out
|
| 207 |
+
torch.cuda.empty_cache()
|
| 208 |
+
return best / 1e3, timed_ok
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def _geomean(xs):
|
| 212 |
+
return math.exp(sum(math.log(max(v, 1e-9)) for v in xs) / len(xs)) if xs else 0.0
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def main():
|
| 216 |
+
details, correct_gate, geo = {}, False, 0.0
|
| 217 |
+
try:
|
| 218 |
+
spec = importlib.util.spec_from_file_location("submission", MODULE_PATH)
|
| 219 |
+
m = importlib.util.module_from_spec(spec)
|
| 220 |
+
spec.loader.exec_module(m)
|
| 221 |
+
fn = m.sta_backward
|
| 222 |
+
|
| 223 |
+
corr_ok, msg = True, ""
|
| 224 |
+
for i, shp in enumerate(CORRECT_SHAPES):
|
| 225 |
+
args = _mk(*shp, seed=10 + i)
|
| 226 |
+
ok, val, m_ = _check(fn(*args), _ref(*args))
|
| 227 |
+
if not ok:
|
| 228 |
+
corr_ok, msg = False, f"cfg{i} {shp} {m_}"
|
| 229 |
+
break
|
| 230 |
+
del args
|
| 231 |
+
torch.cuda.empty_cache()
|
| 232 |
+
details["correct_msg"] = msg or "all correctness shapes pass"
|
| 233 |
+
|
| 234 |
+
vals, per_shape, perf_ok = [], [], corr_ok
|
| 235 |
+
for i, shp in enumerate(GRADER_SHAPES):
|
| 236 |
+
args = _mk(*shp, seed=100 + i)
|
| 237 |
+
ok, val, m_ = _check(fn(*args), _ref(*args))
|
| 238 |
+
if not ok:
|
| 239 |
+
perf_ok = False
|
| 240 |
+
del args
|
| 241 |
+
torch.cuda.empty_cache()
|
| 242 |
+
t, timed_ok = _bench_fresh(fn, lambda s, _p=shp: _mk(*_p, seed=s))
|
| 243 |
+
if not timed_ok:
|
| 244 |
+
perf_ok = False
|
| 245 |
+
v = canonical_work(*shp) / t / 1e12 if t > 0 else 0.0
|
| 246 |
+
vals.append(v)
|
| 247 |
+
per_shape.append({"shape": list(shp), "tflops": round(v, 3), "ms": round(t * 1e3, 3),
|
| 248 |
+
"check": m_, "timed_ok": timed_ok})
|
| 249 |
+
geo = _geomean(vals)
|
| 250 |
+
details.update(per_shape=per_shape, geomean=round(geo, 4), perf_size_ok=perf_ok)
|
| 251 |
+
correct_gate = corr_ok and perf_ok
|
| 252 |
+
except Exception as e:
|
| 253 |
+
details["error"] = f"{e.__class__.__name__}: {e}"[:220]
|
| 254 |
+
details["trace"] = traceback.format_exc()[-800:]
|
| 255 |
+
|
| 256 |
+
reward = round(geo, 4) if correct_gate else 0.0
|
| 257 |
+
os.makedirs(REWARD_DIR, exist_ok=True)
|
| 258 |
+
json.dump({"reward": reward, "correct": 1.0 if correct_gate else 0.0,
|
| 259 |
+
"geomean": round(geo, 4), "metric": "TFLOP/s (geomean over graded shapes)"},
|
| 260 |
+
open(f"{REWARD_DIR}/reward.json", "w"), indent=2)
|
| 261 |
+
open(f"{REWARD_DIR}/reward.txt", "w").write(str(reward))
|
| 262 |
+
json.dump(details, open(f"{REWARD_DIR}/details.json", "w"), indent=2, default=str)
|
| 263 |
+
print("reward:", reward, "TFLOP/s | correct:", 1.0 if correct_gate else 0.0)
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
main()
|
tasks/video-sparse-attention/sta-ragged-tile-boundary/RUN.md
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Running `sta-ragged-tile-boundary`
|
| 2 |
+
|
| 3 |
+
Real video latents do not divide by the tile: HunyuanVideo at 720p is 33 x 45 x 80 and every tile size anyone actually uses leaves a remainder on all three axes. That single fact removes the two things every tiled attention kernel relies on — the tile-major reshape and the constant key count — because the boundary tiles are SHORT, the window that reaches them is short with them, and no two query tiles need the same amount of work. Ceil-divide the grid, clamp the window inward, and attend over a 3D box whose size changes from tile to tile.
|
| 4 |
+
|
| 5 |
+
| | |
|
| 6 |
+
|---|---|
|
| 7 |
+
| **Task id** | `mle-bench/sta-ragged-tile-boundary` |
|
| 8 |
+
| **Group** | `kernel-generation` |
|
| 9 |
+
| **GPUs** | 1 |
|
| 10 |
+
| **Agent edits** | `/app/sta_ragged.py` |
|
| 11 |
+
| **Score** | achieved **TFLOP/s** (uncapped speed leaderboard), `0` if incorrect |
|
| 12 |
+
| **Grade output** | `tests/test.sh` -> `/logs/verifier/reward.json` |
|
| 13 |
+
|
| 14 |
+
## Run through harbor
|
| 15 |
+
|
| 16 |
+
```bash
|
| 17 |
+
harbor run --dataset-path kernel-generation/kernels/sta-ragged-tile-boundary --task-name sta-ragged-tile-boundary \
|
| 18 |
+
--agent claude-code --model anthropic/claude-opus-4-1 -e docker
|
| 19 |
+
```
|
| 20 |
+
|
| 21 |
+
## Run manually
|
| 22 |
+
|
| 23 |
+
```bash
|
| 24 |
+
cd kernel-generation/kernels/sta-ragged-tile-boundary
|
| 25 |
+
docker build -t sta-ragged-tile-boundary environment/
|
| 26 |
+
docker run -d --name v --gpus '"device=0"' --shm-size=8g --entrypoint sleep sta-ragged-tile-boundary infinity
|
| 27 |
+
docker cp tests v:/tests && docker exec v bash /tests/test.sh # untouched start -> reward 0.0
|
| 28 |
+
docker rm -f v
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
Use an **idle** GPU: the score is a timing measurement.
|
| 32 |
+
|
| 33 |
+
## Design
|
| 34 |
+
|
| 35 |
+
Correctness is a hard gate; the score is an absolute hardware metric (TFLOP/s), so the task is
|
| 36 |
+
hardware-portable and needs no gold solution, no oracle, and nothing vendored or sealed.
|
| 37 |
+
|
| 38 |
+
Anti-cheat is structural: the image holds only the permitted toolchain and has no internet; the grader is
|
| 39 |
+
copied in at grade time with its own private copy of the reference; and every timed rep runs on fresh inputs
|
| 40 |
+
with the timed output itself validated, so memoize-and-replay fails the gate.
|
| 41 |
+
|
| 42 |
+
Generated by `_factory/build.py` — edit the spec and regenerate rather than editing this task by hand.
|
tasks/video-sparse-attention/sta-ragged-tile-boundary/environment/CLAUDE.md
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Working in this environment
|
| 2 |
+
|
| 3 |
+
## ⚠️ Stop background processes without killing yourself
|
| 4 |
+
|
| 5 |
+
You are launched as `claude --print -- '<the task instruction>'`, so the task text — including the
|
| 6 |
+
file names and commands it mentions — is on **your own** process's command line. Any command that
|
| 7 |
+
finds processes by **matching that text** (`pkill -f …`, `pgrep -f … | xargs kill`, a `/proc`
|
| 8 |
+
cmdline scan, `fuser -k`, `killall`) can match and **kill the agent itself**, ending your run
|
| 9 |
+
(`NonZeroAgentExitCodeError`) and grading you on unfinished work.
|
| 10 |
+
|
| 11 |
+
This bites whenever you background something and later stop/restart it — a **server**, a long
|
| 12 |
+
**build** or **training run**, or an **ncu / nsys profiling** session.
|
| 13 |
+
|
| 14 |
+
**Always** manage a background process by its **exact recorded PID**, never by a name pattern:
|
| 15 |
+
|
| 16 |
+
```bash
|
| 17 |
+
nohup <your command> > /tmp/job.log 2>&1 & echo $! > /tmp/job.pid # start + record the PID
|
| 18 |
+
kill "$(cat /tmp/job.pid)"; sleep 3 # stop (SIGTERM); -9 only if needed
|
| 19 |
+
```
|
| 20 |
+
|
| 21 |
+
Use `setsid` and kill the process **group** (`kill -- -"$(cat /tmp/job.pid)"`) if it spawns children.
|
| 22 |
+
If you must enumerate processes, match a **unique token that is NOT anywhere in this prompt** and
|
| 23 |
+
**exclude any cmdline containing `claude` or `--print`** — `pgrep -af`, and look before you kill.
|
| 24 |
+
|
| 25 |
+
Full details + safe recipes: **`/app/PROCESS_MANAGEMENT.md`**.
|
tasks/video-sparse-attention/sta-ragged-tile-boundary/environment/Dockerfile
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Kernel-generation task: Write a fast ragged-tile 3D sliding-window video attention kernel
|
| 2 |
+
#
|
| 3 |
+
# Real video latents do not divide by the tile: HunyuanVideo at 720p is 33 x 45 x 80 and every tile size anyone actually uses leaves a remainder on all three axes. That single fact removes the two things every tiled attention kernel relies on — the tile-major reshape and the constant key count — because the boundary tiles are SHORT, the window that reaches them is short with them, and no two query tiles need the same amount of work. Ceil-divide the grid, clamp the window inward, and attend over a 3D box whose size changes from tile to tile.
|
| 4 |
+
#
|
| 5 |
+
# SCORING: correctness is a hard gate; the score is achieved TFLOP/s (uncapped leaderboard, 0 if wrong).
|
| 6 |
+
# There is no gold solution and no oracle, so nothing has to be vendored or sealed.
|
| 7 |
+
#
|
| 8 |
+
# TOOLCHAIN POLICY: the agent writes the kernel with Triton (+Gluon), CUDA C++ via nvcc, CUTLASS headers, or
|
| 9 |
+
# the CuTe DSL. Enforcement is by ABSENCE, not by scanning: only the permitted toolchain is installed and
|
| 10 |
+
# there is no internet, so nothing else can be obtained.
|
| 11 |
+
#
|
| 12 |
+
# GENERATED by _factory/build.py.
|
| 13 |
+
FROM pytorch/pytorch:2.11.0-cuda12.8-cudnn9-devel
|
| 14 |
+
|
| 15 |
+
# NOTE: every heavy layer comes FIRST and depends only on {base_image, pip_extra}, so all tasks in this
|
| 16 |
+
# lane share the same cached layers. The task-specific COPYs are LAST. Do not reorder.
|
| 17 |
+
RUN pip install --break-system-packages --no-cache-dir einops nvidia-cutlass-dsl && \
|
| 18 |
+
apt-get update && apt-get install -y --no-install-recommends iptables iproute2 curl ca-certificates build-essential git && \
|
| 19 |
+
curl -LsSf https://astral.sh/uv/install.sh | sh && \
|
| 20 |
+
/root/.local/bin/uv tool install mini-swe-agent
|
| 21 |
+
# header-only CUTLASS for the agent's CUDA/CuTe route
|
| 22 |
+
RUN git clone --depth 1 https://github.com/NVIDIA/cutlass /opt/cutlass && rm -rf /opt/cutlass/.git
|
| 23 |
+
# pre-bake Claude Code; harbor's claude_code.install() skips when present
|
| 24 |
+
RUN curl -fsSL https://deb.nodesource.com/setup_22.x | bash - && \
|
| 25 |
+
apt-get install -y nodejs procps && \
|
| 26 |
+
npm install -g @anthropic-ai/claude-code && claude --version
|
| 27 |
+
ENV PATH=/root/.local/bin:$PATH
|
| 28 |
+
ENV DISABLE_TELEMETRY=1 DISABLE_AUTOUPDATER=1 DISABLE_ERROR_REPORTING=1 CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1
|
| 29 |
+
|
| 30 |
+
COPY restrict-network.sh /app/restrict-network.sh
|
| 31 |
+
RUN chmod +x /app/restrict-network.sh
|
| 32 |
+
# strip apt sources LAST so harbor's post-firewall apt step is a no-op that succeeds
|
| 33 |
+
RUN rm -rf /var/lib/apt/lists/* /etc/apt/sources.list /etc/apt/sources.list.d
|
| 34 |
+
|
| 35 |
+
WORKDIR /app
|
| 36 |
+
COPY CLAUDE.md PROCESS_MANAGEMENT.md /app/
|
| 37 |
+
|
| 38 |
+
# task-specific files LAST so the layers above stay shared across every task
|
| 39 |
+
COPY reference.py /app/reference.py
|
| 40 |
+
COPY measure.py /app/measure.py
|
| 41 |
+
COPY sta_ragged.py /app/sta_ragged.py
|
tasks/video-sparse-attention/sta-ragged-tile-boundary/environment/PROCESS_MANAGEMENT.md
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Managing background processes — READ THIS before you `kill` anything
|
| 2 |
+
|
| 3 |
+
You may start and stop background processes while iterating — a **server**, a long **build** or
|
| 4 |
+
**training run**, or an **ncu / nsys profiling** session. **The way you stop one can silently kill
|
| 5 |
+
*your own agent process* and end the whole run.** This has happened repeatedly, including via a
|
| 6 |
+
hand-rolled `/proc` scan — not just `pkill`. Read this once and follow the safe recipe.
|
| 7 |
+
|
| 8 |
+
## The trap: matching task text against process command lines
|
| 9 |
+
|
| 10 |
+
You were launched as roughly:
|
| 11 |
+
|
| 12 |
+
```
|
| 13 |
+
claude --print -- '<the entire task instruction text>'
|
| 14 |
+
```
|
| 15 |
+
|
| 16 |
+
The full task instruction is on **your own** process's command line, and it contains the file names
|
| 17 |
+
and commands the task mentions (e.g. `server.py`, `build.sh`, `train.py`, `solution.cu`, `/app/...`).
|
| 18 |
+
So **any** command that finds processes by matching those strings will match — and can kill — **the
|
| 19 |
+
agent itself**:
|
| 20 |
+
|
| 21 |
+
```
|
| 22 |
+
pkill -9 -f "train.py" # matches the claude agent -> kills YOU
|
| 23 |
+
pgrep -f "server.py" | xargs kill # same: the pid list includes claude
|
| 24 |
+
for p in $(pgrep -f build.sh); do kill -9 $p; done # same
|
| 25 |
+
for pid in /proc/*; do case "$(cmdline)" in *solution*) kill -9 $pid;; esac; done # same
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
It is **not about `pkill`** — it is about **matching a string that appears in your prompt**. `pgrep`,
|
| 29 |
+
a `/proc` scan, `fuser`, or `nvidia-smi`-pid loops all have the same failure if the match pattern (or
|
| 30 |
+
the surviving pid list) includes the `claude` process. When you `kill -9` yourself the run dies
|
| 31 |
+
immediately (`NonZeroAgentExitCodeError`) and you are graded on whatever was already in place — usually
|
| 32 |
+
worse than what you were about to finish.
|
| 33 |
+
|
| 34 |
+
## The one safe rule: kill only the exact PID you recorded
|
| 35 |
+
|
| 36 |
+
**Start** a background job and record its PID in a file:
|
| 37 |
+
|
| 38 |
+
```bash
|
| 39 |
+
nohup <your command> > /tmp/job.log 2>&1 &
|
| 40 |
+
echo $! > /tmp/job.pid
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
**Stop / restart** by that exact PID — never by a name pattern:
|
| 44 |
+
|
| 45 |
+
```bash
|
| 46 |
+
kill "$(cat /tmp/job.pid)" 2>/dev/null # SIGTERM: lets it release the GPU / flush cleanly
|
| 47 |
+
sleep 3
|
| 48 |
+
kill -9 "$(cat /tmp/job.pid)" 2>/dev/null # force only if it did not exit
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
If the job spawns workers, run it in its own process group and signal the group by its (negative)
|
| 52 |
+
PGID — still an exact id, never a pattern:
|
| 53 |
+
|
| 54 |
+
```bash
|
| 55 |
+
setsid <your command> > /tmp/job.log 2>&1 < /dev/null & echo $! > /tmp/job.pid
|
| 56 |
+
kill -TERM -- "-$(cat /tmp/job.pid)" 2>/dev/null
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
## If you ever enumerate processes, EXCLUDE the agent
|
| 60 |
+
|
| 61 |
+
Prefer not to. But if you must scan (e.g. hunting a leaked worker), **exclude the `claude` agent and
|
| 62 |
+
your own shell**, and match on a **unique token that is NOT anywhere in this prompt** — give your job
|
| 63 |
+
a unique name and match only that:
|
| 64 |
+
|
| 65 |
+
```bash
|
| 66 |
+
# job named e.g. job_7x3q9 — a token that appears NOWHERE in the task text
|
| 67 |
+
pgrep -af job_7x3q9 | grep -v -E 'claude|--print|pgrep|grep|bash' # LOOK FIRST
|
| 68 |
+
# only kill pids from THIS filtered list, and never a pid whose cmdline contains 'claude' or '--print'
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
Do **not** add a prompt word (a file name, `/app`, `python3`, …) to the pattern "just in case" — that
|
| 72 |
+
single addition re-introduces the self-kill. Match the unique token **only**.
|
| 73 |
+
|
| 74 |
+
## Freeing the GPU without going nuclear
|
| 75 |
+
|
| 76 |
+
If VRAM stays high after you stop a GPU job, the usual cause is a **child process** or a not-yet-
|
| 77 |
+
collected CUDA context — not a stray process you need to hunt across `/proc`. Do this instead of a
|
| 78 |
+
`/proc` sweep:
|
| 79 |
+
|
| 80 |
+
- Kill the job **by its recorded PID / PGID** (above) and `sleep 5–10`; the CUDA context frees after
|
| 81 |
+
the process fully exits.
|
| 82 |
+
- Make the job release cleanly on `SIGTERM` (drop the model / `torch.cuda.empty_cache()` / exit) so a
|
| 83 |
+
single `kill $PID` is enough.
|
| 84 |
+
- Start it in its own group (`setsid`) so `kill -- -$PGID` takes the workers with it.
|
| 85 |
+
- Check with `nvidia-smi` — if a PID still holds memory, `kill` **that exact numeric PID**, after
|
| 86 |
+
confirming its cmdline is **not** `claude` / `--print`.
|
| 87 |
+
|
| 88 |
+
## Rules of thumb
|
| 89 |
+
|
| 90 |
+
- **Never** match a task-prompt string (`server.py`, `train.py`, `build.sh`, `/app`, `python3`, …)
|
| 91 |
+
with `pkill -f`, `pgrep -f`, `killall`, `fuser`, or a `/proc` cmdline scan — they all can hit the
|
| 92 |
+
agent (its argv holds the prompt).
|
| 93 |
+
- **Always** kill a background job by the exact PID from its pidfile (or its PGID).
|
| 94 |
+
- If you must enumerate, match a **unique token not in the prompt** and **exclude `claude` / `--print`
|
| 95 |
+
and your own shell**; `pgrep -af` and look before you kill.
|
| 96 |
+
- `SIGTERM` first for a clean release; `-9` only as a last resort on a specific numeric PID.
|
tasks/video-sparse-attention/sta-ragged-tile-boundary/environment/docker-compose.yaml
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Anti-cheat firewall overlay, merged on top of Harbor's base compose. Gives the main container
|
| 2 |
+
# NET_ADMIN and runs restrict-network.sh as the entrypoint, so only DNS + the LLM API endpoints are
|
| 3 |
+
# reachable (pypi/github/HF blocked). network_mode stays "public" (see task.toml) — the firewall, not
|
| 4 |
+
# Docker, enforces the allowlist. mini-swe-agent is pre-installed and harbor's patched installer skips
|
| 5 |
+
# the (now-blocked) network install when it is already present.
|
| 6 |
+
services:
|
| 7 |
+
main:
|
| 8 |
+
cap_add:
|
| 9 |
+
- NET_ADMIN
|
| 10 |
+
entrypoint: ["/bin/bash", "/app/restrict-network.sh"]
|
| 11 |
+
environment:
|
| 12 |
+
- ALLOWED_HOSTS=${ALLOWED_HOSTS:-}
|
| 13 |
+
- FIREWORKS_BASE_URL=${FIREWORKS_BASE_URL:-}
|
| 14 |
+
- OPENROUTER_BASE_URL=${OPENROUTER_BASE_URL:-}
|
| 15 |
+
- OPENAI_BASE_URL=${OPENAI_BASE_URL:-}
|
| 16 |
+
- ANTHROPIC_BASE_URL=${ANTHROPIC_BASE_URL:-}
|
| 17 |
+
- LLM_BASE_URL=${LLM_BASE_URL:-}
|
| 18 |
+
- LITELLM_BASE_URL=${LITELLM_BASE_URL:-}
|
tasks/video-sparse-attention/sta-ragged-tile-boundary/environment/measure.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Self-assessment tool — your correctness + achieved TFLOP/s across a RANGE of shapes.
|
| 2 |
+
|
| 3 |
+
python /app/measure.py # the graded regime
|
| 4 |
+
python /app/measure.py --quick # smaller sizes for fast iteration
|
| 5 |
+
|
| 6 |
+
You are scored on the **geomean achieved TFLOP/s** — NOT one fixed size, and the leaderboard is UNCAPPED
|
| 7 |
+
(higher is always better). The shapes below are a DIFFERENT sample from the same regime the grader uses, so
|
| 8 |
+
optimize for GENERALITY. Work is counted with the same shape-only formula the grader uses, so the number
|
| 9 |
+
printed here is computed exactly as your score is.
|
| 10 |
+
|
| 11 |
+
GENERATED by _factory/build.py.
|
| 12 |
+
"""
|
| 13 |
+
import argparse
|
| 14 |
+
import math
|
| 15 |
+
import sys
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
|
| 19 |
+
sys.path.insert(0, "/app")
|
| 20 |
+
from reference import sta_ragged_attention as _ref
|
| 21 |
+
from sta_ragged import sta_ragged_attention as _agent
|
| 22 |
+
|
| 23 |
+
TOL = 0.008
|
| 24 |
+
|
| 25 |
+
FULL = [(1, 17, 21, 25, 12, 128, 4, 6, 7, 3, 3, 3), (1, 13, 25, 29, 16, 128, 3, 7, 8, 3, 3, 3), (1, 19, 23, 27, 12, 128, 5, 6, 7, 3, 3, 3), (2, 11, 19, 21, 16, 128, 3, 5, 6, 3, 3, 3), (1, 17, 25, 31, 16, 64, 4, 7, 8, 3, 3, 3)]
|
| 26 |
+
QUICK = [(1, 11, 13, 17, 8, 128, 2, 3, 4, 3, 3, 3), (1, 9, 11, 13, 8, 64, 2, 2, 3, 3, 3, 3), (2, 7, 9, 15, 6, 128, 2, 2, 4, 3, 3, 3)]
|
| 27 |
+
|
| 28 |
+
def _axis_plan(n, t, w):
|
| 29 |
+
"""Per tile on one axis: (query range, key range) as half-open token intervals. SHAPE ONLY."""
|
| 30 |
+
nt = -(-n // t)
|
| 31 |
+
out = []
|
| 32 |
+
for i in range(nt):
|
| 33 |
+
s = min(max(i - w // 2, 0), nt - w)
|
| 34 |
+
out.append(((i * t, min(n, (i + 1) * t)), (s * t, min(n, (s + w) * t))))
|
| 35 |
+
return out
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def canonical_work(B, F, Hh, Ww, NH, D, TF, TH, TW, WF, WH, WW):
|
| 39 |
+
"""FLOPs attributed to one call, from the SHAPE ALONE.
|
| 40 |
+
|
| 41 |
+
A query tile is the product of its three axis ranges, and its key box is the product of the three
|
| 42 |
+
(clamped, clipped) window ranges -- so both the query count and the key count vary from tile to tile,
|
| 43 |
+
and both follow from the shape. Every (query, key) pair costs 4*D FLOPs.
|
| 44 |
+
"""
|
| 45 |
+
A = _axis_plan(F, TF, WF)
|
| 46 |
+
Bx = _axis_plan(Hh, TH, WH)
|
| 47 |
+
C = _axis_plan(Ww, TW, WW)
|
| 48 |
+
pairs = 0
|
| 49 |
+
for (qa0, qa1), (ka0, ka1) in A:
|
| 50 |
+
for (qb0, qb1), (kb0, kb1) in Bx:
|
| 51 |
+
for (qc0, qc1), (kc0, kc1) in C:
|
| 52 |
+
pairs += ((qa1 - qa0) * (qb1 - qb0) * (qc1 - qc0)) * \
|
| 53 |
+
((ka1 - ka0) * (kb1 - kb0) * (kc1 - kc0))
|
| 54 |
+
return 4 * D * B * NH * pairs
|
| 55 |
+
|
| 56 |
+
def _mk(B, F, Hh, Ww, NH, D, TF, TH, TW, WF, WH, WW, seed):
|
| 57 |
+
gen = torch.Generator(device="cuda").manual_seed(seed)
|
| 58 |
+
T = F * Hh * Ww
|
| 59 |
+
def r():
|
| 60 |
+
return torch.randn(B, T, NH, D, device="cuda", dtype=torch.bfloat16, generator=gen)
|
| 61 |
+
return r(), r(), r(), (F, Hh, Ww), (TF, TH, TW), (WF, WH, WW)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _is_exact(t):
|
| 65 |
+
"""Integer/bool tensors are compared EXACTLY: .float() is lossy above 2**24, so two distinct large
|
| 66 |
+
ids (page ids, token ids, indices) can compare equal and let a wrong kernel pass."""
|
| 67 |
+
return t.dtype in (torch.int8, torch.int16, torch.int32, torch.int64, torch.uint8, torch.bool)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _check(out, ref):
|
| 71 |
+
"""-> (ok, value, msg). Exact for integer/bool; relative Frobenius error otherwise."""
|
| 72 |
+
if out is None or tuple(out.shape) != tuple(ref.shape):
|
| 73 |
+
return False, 1.0, "bad/None shape"
|
| 74 |
+
if _is_exact(ref):
|
| 75 |
+
bad = int((out != ref).sum())
|
| 76 |
+
return bad == 0, float(bad), ("exact match" if bad == 0 else f"{bad} elements differ")
|
| 77 |
+
e = float((out.float() - ref.float()).norm() / (ref.float().norm() + 1e-12))
|
| 78 |
+
return e <= TOL, e, f"relerr {e:.2e}"
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _bench(fn, reps=8, warm=3):
|
| 82 |
+
for _ in range(warm):
|
| 83 |
+
fn()
|
| 84 |
+
torch.cuda.synchronize()
|
| 85 |
+
best = float("inf")
|
| 86 |
+
for _ in range(reps):
|
| 87 |
+
s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
|
| 88 |
+
s.record()
|
| 89 |
+
fn()
|
| 90 |
+
e.record()
|
| 91 |
+
torch.cuda.synchronize()
|
| 92 |
+
best = min(best, s.elapsed_time(e))
|
| 93 |
+
return best / 1e3
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def main():
|
| 97 |
+
ap = argparse.ArgumentParser()
|
| 98 |
+
ap.add_argument("--quick", action="store_true")
|
| 99 |
+
a = ap.parse_args()
|
| 100 |
+
shapes = QUICK if a.quick else FULL
|
| 101 |
+
print(f"geomean over {len(shapes)} shapes ({'quick' if a.quick else 'full'}); the grader uses "
|
| 102 |
+
f"DIFFERENT sizes in the same regime — optimize for generality\n")
|
| 103 |
+
vals, allok = [], True
|
| 104 |
+
for shp in shapes:
|
| 105 |
+
args = _mk(*shp, seed=sum(int(x) for x in shp) % 9973)
|
| 106 |
+
ref = _ref(*args)
|
| 107 |
+
try:
|
| 108 |
+
out = _agent(*args)
|
| 109 |
+
except Exception as ex:
|
| 110 |
+
print(f" {shp}: RAISED {type(ex).__name__}: {str(ex)[:70]}")
|
| 111 |
+
allok = False
|
| 112 |
+
continue
|
| 113 |
+
ok, val, msg = _check(out, ref)
|
| 114 |
+
allok = allok and ok
|
| 115 |
+
t = _bench(lambda: _agent(*args))
|
| 116 |
+
v = canonical_work(*shp) / t / 1e12 if t > 0 else 0.0
|
| 117 |
+
vals.append(v)
|
| 118 |
+
print(f" {str(shp):28s} {t*1e3:9.2f} ms | {v:9.2f} TFLOP/s | {msg} {'ok' if ok else 'FAIL'}")
|
| 119 |
+
del args, ref, out
|
| 120 |
+
torch.cuda.empty_cache()
|
| 121 |
+
geo = math.exp(sum(math.log(max(v, 1e-9)) for v in vals) / len(vals)) if vals else 0.0
|
| 122 |
+
print(f"\n => GEOMEAN {geo:.2f} TFLOP/s "
|
| 123 |
+
f"({'all correct' if allok else 'SOME WRONG — a wrong kernel scores 0, fix correctness first'})")
|
| 124 |
+
print(" This IS your score, and it is uncapped — higher is always better. Keep pushing.")
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
if __name__ == "__main__":
|
| 128 |
+
main()
|
tasks/video-sparse-attention/sta-ragged-tile-boundary/environment/reference.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Reference implementation — the CORRECTNESS SPEC for `sta_ragged_attention`.
|
| 2 |
+
|
| 3 |
+
This is correct but slow. It defines exactly what your kernel must reproduce; its speed has no
|
| 4 |
+
bearing on your score, which is an absolute TFLOP/s number. GENERATED by _factory/build.py.
|
| 5 |
+
"""
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def _axis_plan(n, t, w):
|
| 10 |
+
"""Per tile on one axis: (query range, key range) as half-open token intervals. SHAPE ONLY.
|
| 11 |
+
|
| 12 |
+
The axis is CEIL-divided into nt tiles, so the last one holds n - (nt-1)*t tokens. The window is nt-tile
|
| 13 |
+
centred and shifted inward so it never leaves the axis, then converted to tokens and clipped at n.
|
| 14 |
+
"""
|
| 15 |
+
nt = -(-n // t)
|
| 16 |
+
out = []
|
| 17 |
+
for i in range(nt):
|
| 18 |
+
s = min(max(i - w // 2, 0), nt - w)
|
| 19 |
+
out.append(((i * t, min(n, (i + 1) * t)), (s * t, min(n, (s + w) * t))))
|
| 20 |
+
return out
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def sta_ragged_attention(q, k, v, latent, tile, window, scale=None):
|
| 24 |
+
"""Ragged sliding-tile attention, written as one dense softmax per query tile over its 3D key box.
|
| 25 |
+
|
| 26 |
+
Correct and simple — it is the numerical SPECIFICATION, not a performance target: it materialises the
|
| 27 |
+
whole gathered key box of every query tile.
|
| 28 |
+
"""
|
| 29 |
+
B, T, NH, D = q.shape
|
| 30 |
+
F, Hh, Ww = latent
|
| 31 |
+
tf, th, tw = tile
|
| 32 |
+
wf, wh, ww = window
|
| 33 |
+
if scale is None:
|
| 34 |
+
scale = D ** -0.5
|
| 35 |
+
dev = q.device
|
| 36 |
+
|
| 37 |
+
qv = q.float().view(B, F, Hh, Ww, NH, D)
|
| 38 |
+
kv = k.float().view(B, F, Hh, Ww, NH, D)
|
| 39 |
+
vv = v.float().view(B, F, Hh, Ww, NH, D)
|
| 40 |
+
o = torch.empty(B, F, Hh, Ww, NH, D, device=dev, dtype=torch.float32)
|
| 41 |
+
|
| 42 |
+
for (qf0, qf1), (kf0, kf1) in _axis_plan(F, tf, wf):
|
| 43 |
+
for (qh0, qh1), (kh0, kh1) in _axis_plan(Hh, th, wh):
|
| 44 |
+
for (qw0, qw1), (kw0, kw1) in _axis_plan(Ww, tw, ww):
|
| 45 |
+
qc = qv[:, qf0:qf1, qh0:qh1, qw0:qw1].reshape(B, -1, NH, D)
|
| 46 |
+
kc = kv[:, kf0:kf1, kh0:kh1, kw0:kw1].reshape(B, -1, NH, D)
|
| 47 |
+
vc = vv[:, kf0:kf1, kh0:kh1, kw0:kw1].reshape(B, -1, NH, D)
|
| 48 |
+
s = torch.einsum("bqhd,bkhd->bhqk", qc * scale, kc)
|
| 49 |
+
oc = torch.einsum("bhqk,bkhd->bqhd", torch.softmax(s, dim=-1), vc)
|
| 50 |
+
o[:, qf0:qf1, qh0:qh1, qw0:qw1] = oc.view(B, qf1 - qf0, qh1 - qh0, qw1 - qw0, NH, D)
|
| 51 |
+
return o.view(B, T, NH, D)
|
tasks/video-sparse-attention/sta-ragged-tile-boundary/environment/restrict-network.sh
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Outbound firewall (anti-cheat): allow ONLY DNS, loopback, docker-internal networks, and the LLM API
|
| 3 |
+
# endpoints the agent needs. Everything else is dropped — in particular pypi, github, and huggingface,
|
| 4 |
+
# so the agent cannot `pip install vllm` / `pip install sglang` / clone the reference moe_align kernel and
|
| 5 |
+
# copy it. torch + triton are already in the image, and mini-swe-agent is pre-installed (harbor's patched
|
| 6 |
+
# installer skips the network install when it is already present), so no package index is needed at run time.
|
| 7 |
+
#
|
| 8 |
+
# Runs as the container ENTRYPOINT before the CMD. iptables rules are network-namespace-wide, so they also
|
| 9 |
+
# apply to the agent's `docker exec` commands. Requires cap_add: NET_ADMIN.
|
| 10 |
+
set -uo pipefail
|
| 11 |
+
|
| 12 |
+
# LLM API endpoints the agent may reach. Extend at launch via ALLOWED_HOSTS=host1,host2 (no scheme).
|
| 13 |
+
API_HOSTS=(
|
| 14 |
+
api.fireworks.ai
|
| 15 |
+
openrouter.ai openrouter.io
|
| 16 |
+
api.openai.com api.anthropic.com generativelanguage.googleapis.com
|
| 17 |
+
api.together.xyz integrate.api.nvidia.com api.moonshot.cn api.kimi.com
|
| 18 |
+
)
|
| 19 |
+
# Auto-allow hosts from any *_BASE_URL / *_ENDPOINT env var (ANTHROPIC_BASE_URL, OPENAI_BASE_URL, …).
|
| 20 |
+
CUSTOM=()
|
| 21 |
+
while IFS='=' read -r n v; do
|
| 22 |
+
case "$n" in
|
| 23 |
+
*_BASE_URL|*_URL|*_ENDPOINT)
|
| 24 |
+
[ -n "$v" ] && CUSTOM+=("$(echo "$v" | sed 's|.*://||; s|[:/].*||')") ;;
|
| 25 |
+
esac
|
| 26 |
+
done < <(env)
|
| 27 |
+
if [ -n "${ALLOWED_HOSTS:-}" ]; then IFS=',' read -ra E <<< "$ALLOWED_HOSTS"; CUSTOM+=("${E[@]}"); fi
|
| 28 |
+
ALL_HOSTS=("${API_HOSTS[@]}" ${CUSTOM[@]+"${CUSTOM[@]}"})
|
| 29 |
+
|
| 30 |
+
if iptables -L OUTPUT -n >/dev/null 2>&1; then
|
| 31 |
+
echo "restrict-network: applying outbound allowlist firewall..."
|
| 32 |
+
iptables -F OUTPUT 2>/dev/null || true
|
| 33 |
+
iptables -A OUTPUT -o lo -j ACCEPT
|
| 34 |
+
iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
|
| 35 |
+
iptables -A OUTPUT -p udp --dport 53 -j ACCEPT
|
| 36 |
+
iptables -A OUTPUT -p tcp --dport 53 -j ACCEPT
|
| 37 |
+
iptables -A OUTPUT -d 10.0.0.0/8 -j ACCEPT
|
| 38 |
+
iptables -A OUTPUT -d 172.16.0.0/12 -j ACCEPT
|
| 39 |
+
iptables -A OUTPUT -d 192.168.0.0/16 -j ACCEPT
|
| 40 |
+
iptables -A OUTPUT -d 127.0.0.11 -j ACCEPT
|
| 41 |
+
for h in "${ALL_HOSTS[@]}"; do
|
| 42 |
+
for ip in $(getent ahosts "$h" 2>/dev/null | awk '{print $1}' | sort -u); do
|
| 43 |
+
iptables -A OUTPUT -d "$ip" -j ACCEPT
|
| 44 |
+
done
|
| 45 |
+
done
|
| 46 |
+
iptables -A OUTPUT -j REJECT --reject-with icmp-admin-prohibited
|
| 47 |
+
echo "restrict-network: outbound locked to DNS + LLM endpoints; pypi/github/HF blocked."
|
| 48 |
+
else
|
| 49 |
+
echo "restrict-network: WARNING — iptables unavailable (need cap_add NET_ADMIN); NOT firewalled." >&2
|
| 50 |
+
fi
|
| 51 |
+
|
| 52 |
+
exec "$@"
|
tasks/video-sparse-attention/sta-ragged-tile-boundary/environment/sta_ragged.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Your implementation goes here.
|
| 2 |
+
|
| 3 |
+
Replace the body of `sta_ragged_attention` with a FAST implementation that reproduces the output of /app/reference.py
|
| 4 |
+
(same signature, same numerics within tolerance) but is much faster — see /app/instruction.md.
|
| 5 |
+
Run `python /app/measure.py` to check your correctness and achieved TFLOP/s.
|
| 6 |
+
|
| 7 |
+
You may add helper modules, Triton kernels, CUDA extensions, caches, etc. — only this function's name,
|
| 8 |
+
signature and returned value are fixed by the contract.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def sta_ragged_attention(q, k, v, latent, tile, window, scale=None):
|
| 13 |
+
"""Sliding-tile 3D window attention on a latent that does NOT divide by the tile size.
|
| 14 |
+
|
| 15 |
+
Args:
|
| 16 |
+
q, k, v: (B, T, NH, D) bfloat16 — T = F*Hh*Ww latent tokens in RASTER order (f, then h, then w).
|
| 17 |
+
latent: (F, Hh, Ww) tuple of int — latent grid; NONE of these need be a multiple of the tile.
|
| 18 |
+
tile: (tf, th, tw) tuple of int — 3D tile size; the grid is ceil-divided, so the last tile on each
|
| 19 |
+
axis is SHORT.
|
| 20 |
+
window: (wf, wh, ww) tuple of int — window size in TILES on each axis; each is <= the tile count of
|
| 21 |
+
that axis and is odd.
|
| 22 |
+
scale: float or None — logit scale; None means D ** -0.5.
|
| 23 |
+
|
| 24 |
+
Returns:
|
| 25 |
+
o: (B, T, NH, D), bfloat16 or float32, RASTER order — must match /app/reference.py numerically.
|
| 26 |
+
"""
|
| 27 |
+
raise NotImplementedError("Implement a fast sta_ragged_attention in /app/sta_ragged.py")
|
tasks/video-sparse-attention/sta-ragged-tile-boundary/instruction.md
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Write a fast ragged-tile 3D sliding-window video attention kernel
|
| 2 |
+
|
| 3 |
+
You are given a **correct but slow** reference at **`/app/reference.py`** — `sta_ragged_attention(q, k, v, latent, tile, window, scale=None)`. **Read it, run it, profile it.**
|
| 4 |
+
|
| 5 |
+
Write **`/app/sta_ragged.py`** with the **same signature** and the **same numerical output**, but **as fast as you can make it**.
|
| 6 |
+
|
| 7 |
+
```python
|
| 8 |
+
def sta_ragged_attention(q, k, v, latent, tile, window, scale=None):
|
| 9 |
+
...
|
| 10 |
+
```
|
| 11 |
+
|
| 12 |
+
## The computation (this is the exact spec)
|
| 13 |
+
|
| 14 |
+
The latent is `F x Hh x Ww` tokens, flattened raster (`f`, then `h`, then `w`). It is cut into
|
| 15 |
+
3D tiles of `(tf, th, tw)` — but **none of the three dimensions has to divide**. Each axis is **ceil**-divided:
|
| 16 |
+
|
| 17 |
+
```
|
| 18 |
+
nt = ceil(n / t) # tiles on this axis
|
| 19 |
+
tile i covers tokens [ i*t , min(n, (i+1)*t) )
|
| 20 |
+
```
|
| 21 |
+
|
| 22 |
+
so the **last tile on each axis is short** (it can be as short as one token), and there is no reshape that
|
| 23 |
+
turns the sequence into tile-major order.
|
| 24 |
+
|
| 25 |
+
**The window** is `(wf, wh, ww)` tiles, centred on the query tile and **shifted inward** so that it never
|
| 26 |
+
leaves the volume — the standard sliding-tile rule, applied independently on each axis in TILE space:
|
| 27 |
+
|
| 28 |
+
```
|
| 29 |
+
s = clamp(i - w//2, 0, nt - w) # first key TILE on this axis
|
| 30 |
+
key tokens on this axis: [ s*t , min(n, (s+w)*t) )
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
The key set of a query tile is the **3D box** formed by the three axis ranges, and every query in that tile
|
| 34 |
+
attends to all of it with a single softmax:
|
| 35 |
+
|
| 36 |
+
```
|
| 37 |
+
o_t = softmax_r( scale * q_t . k_r ) @ v , r in the box of t's tile
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
**Both counts vary.** A query tile holds between `1` and `tf*th*tw` tokens. Its key box holds between
|
| 41 |
+
`(wf-1)*tf+1` ... `wf*tf` tokens on the `f` axis (and likewise on the others), because the window can contain
|
| 42 |
+
the short last tile — and when `w == nt` the clamp pins every tile to the same box. Two neighbouring query
|
| 43 |
+
tiles routinely have different query counts *and* different key counts.
|
| 44 |
+
|
| 45 |
+
There is no mask beyond the box, no causality, and no text stream. Attention inside the box is dense and
|
| 46 |
+
bidirectional.
|
| 47 |
+
|
| 48 |
+
`/app/reference.py` walks the tile grid and runs one dense softmax per tile over its sliced key box. That is
|
| 49 |
+
the exact specification; it is deliberately simple rather than fast.
|
| 50 |
+
|
| 51 |
+
## The contract (fixed — do not change these)
|
| 52 |
+
|
| 53 |
+
| arg | shape | dtype | meaning |
|
| 54 |
+
|-----|-------|-------|---------|
|
| 55 |
+
| `q`, `k`, `v` | `(B, T, NH, D)` | `bfloat16` | latent tokens, `T = F*Hh*Ww`, RASTER order |
|
| 56 |
+
| `latent` | `(F, Hh, Ww)` | tuple of int | latent grid; **not** multiples of the tile |
|
| 57 |
+
| `tile` | `(tf, th, tw)` | tuple of int | 3D tile size; the grid is ceil-divided |
|
| 58 |
+
| `window` | `(wf, wh, ww)` | tuple of int | window in TILES; odd, and `w <= nt` on that axis |
|
| 59 |
+
| `scale` | scalar | `float` or `None` | logit scale; `None` means `D ** -0.5` |
|
| 60 |
+
|
| 61 |
+
**Return** `o` of shape `(B, T, NH, D)` in the **same raster order as `q`**, `bfloat16` or `float32`.
|
| 62 |
+
|
| 63 |
+
Every graded shape is ragged on **at least two axes**, and `F`, `Hh`, `Ww`, `tf`, `th`, `tw` are frequently
|
| 64 |
+
odd or prime. `w == 1` occurs (the window is then the query tile itself, short tail included). All tensors
|
| 65 |
+
are CUDA, contiguous and read-only.
|
| 66 |
+
|
| 67 |
+
No GQA, no RoPE, no dropout, no causal mask.
|
| 68 |
+
|
| 69 |
+
**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): latents of
|
| 70 |
+
`F` 11-21 by `Hh` 19-27 by `Ww` 23-31 (5k-15k tokens) with tiles of 3-8 on each axis and a 3x3x3 tile window,
|
| 71 |
+
`NH` 12-20 heads, `D` in {64, 128}, `B` 1-2. That is 0.2-0.5 TFLOP per call, at 30-60% of the dense cost —
|
| 72 |
+
the grids are deliberately small enough (4-6 tiles per axis) that **most tiles are boundary tiles**.
|
| 73 |
+
|
| 74 |
+
This is the regime real video latents live in: 33 x 45 x 80 with a (6,8,8) tile is 6 x 6 x 10 tiles, of which
|
| 75 |
+
only 1 in 5 is interior.
|
| 76 |
+
|
| 77 |
+
## How success is decided (runs on GPU)
|
| 78 |
+
|
| 79 |
+
**1. Correctness — a required gate.** The output must match the reference (evaluated in fp32) within **relative Frobenius
|
| 80 |
+
error `8e-3`** at every graded shape, including the timed ones. The boundary tiles are the majority of the
|
| 81 |
+
output, so getting only the interior right scores **0**. A wrong kernel scores **0**, no matter how fast.
|
| 82 |
+
|
| 83 |
+
**2. Performance — this is your score, and it is an UNCAPPED leaderboard.**
|
| 84 |
+
|
| 85 |
+
```
|
| 86 |
+
reward = geomean over graded shapes of ( canonical_work(shape) / your_runtime ) [TFLOP/s]
|
| 87 |
+
reward = 0 if the submission is wrong at any graded shape
|
| 88 |
+
```
|
| 89 |
+
|
| 90 |
+
`canonical_work` depends **only on the shape**, never on how you implemented it, so every submission is
|
| 91 |
+
credited the same work and this is a pure speed ranking in useful units:
|
| 92 |
+
|
| 93 |
+
```
|
| 94 |
+
per axis: nt = ceil(n/t); tile i covers tokens [i*t, min(n,(i+1)*t))
|
| 95 |
+
window start s = clamp(i - w//2, 0, nt-w); keys [s*t, min(n,(s+w)*t))
|
| 96 |
+
FLOPs = 4 * D * B * NH * sum over the 3D tile grid of (query count) * (key count)
|
| 97 |
+
```
|
| 98 |
+
|
| 99 |
+
**There is no cap and no target.** Higher TFLOP/s is always a strictly better score, so **push the
|
| 100 |
+
performance as hard as you can**. Getting a correct implementation is the *start* of the task, not the end of
|
| 101 |
+
it. Once correct, spend the entire remainder of your budget profiling and optimising, re-checking correctness
|
| 102 |
+
after every change. **Use your full time budget.**
|
| 103 |
+
|
| 104 |
+
Run **`python /app/measure.py`** at any point to see your per-shape and geomean TFLOP/s plus correctness.
|
| 105 |
+
|
| 106 |
+
## Where the performance comes from
|
| 107 |
+
|
| 108 |
+
**Do not reshape.** There is no tile-major permutation of a ragged grid, so the tile -> token
|
| 109 |
+
map has to be arithmetic: token `(f,h,w)` lives at `((f*Hh)+h)*Ww + w`, and a query tile is `tf*th` runs of
|
| 110 |
+
`tw*D` contiguous elements with strides `Ww*D` and `Hh*Ww*D`. Compute the three ranges once per tile (six
|
| 111 |
+
integers), then index with two nested strides. A pre-pass that gathers tiles into a padded tile-major buffer
|
| 112 |
+
costs one extra read and one extra write of the whole latent and wastes up to `tf*th*tw / (actual tokens)` of
|
| 113 |
+
every boundary tile.
|
| 114 |
+
|
| 115 |
+
**Key boxes are shared.** All tiles with the same window start on an axis see the same range on that axis —
|
| 116 |
+
and with `nt` only 4-6 and `w = 3`, the clamp means the *first two* and the *last two* tiles share a start.
|
| 117 |
+
Process query tiles grouped by their key box: the box's K/V then loads once into shared memory and serves
|
| 118 |
+
several query tiles.
|
| 119 |
+
|
| 120 |
+
**The work per tile is ragged, so a fixed grid wastes waves.** A one-CTA-per-tile launch runs at the pace of
|
| 121 |
+
the largest tile; the short tail tiles finish early and idle. Either persist CTAs and pull query tiles from a
|
| 122 |
+
counter, or flatten (query tile, key block) pairs into a work list with a prefix sum.
|
| 123 |
+
|
| 124 |
+
**Predicate, do not pad.** The MMA wants a multiple of 16 on both axes and your tiles are 60, 168, 210 tokens
|
| 125 |
+
long. Padding K with zeros injects `exp(0)` into the softmax and is silently wrong; padding with `-inf`
|
| 126 |
+
logits is correct but wastes the lanes. Predicated loads plus a masked score fill is the honest version, and
|
| 127 |
+
the tail is small enough that it should not cost you much.
|
| 128 |
+
|
| 129 |
+
**`D` is 64 or 128, and the key box is 2k-8k tokens** — this is a normal flash-attention inner loop once the
|
| 130 |
+
indexing is solved. Online softmax, fp32 accumulators, K/V staged through shared memory, and reuse the query
|
| 131 |
+
tile across the whole box.
|
| 132 |
+
|
| 133 |
+
## Precision and faithfulness (read this)
|
| 134 |
+
|
| 135 |
+
All tensors are **bfloat16**; the output may be bf16 or fp32.
|
| 136 |
+
|
| 137 |
+
Matmuls on bf16 tensor cores with **fp32 accumulation**; online-softmax state in fp32. An independent
|
| 138 |
+
flash-style implementation (fp32 accumulators, `p` cast to bf16 for the PV matmul, bf16 output) differs from
|
| 139 |
+
the fp32 reference by about `2e-3` relative, flat in problem size; the gate is `8e-3`.
|
| 140 |
+
|
| 141 |
+
**The one precision trap here is padding.** Every boundary tile is short, so both the query axis and the key
|
| 142 |
+
axis of the score block are ragged. A key lane that is out of range must contribute **zero probability** —
|
| 143 |
+
set its logit to `-inf` (or mask after the exponential), never to `0`, and never leave a stale value in the
|
| 144 |
+
accumulator. `exp(0) = 1` on a padded lane is a 1-in-`nkeys` error that shows up as a smooth bias across the
|
| 145 |
+
boundary of every frame, which is exactly the kind of error the faithfulness rule forbids.
|
| 146 |
+
|
| 147 |
+
A query lane that is out of range must not write anything back.
|
| 148 |
+
|
| 149 |
+
Do **not** infer from the reference that fp32 storage is wanted; it computes in fp32 purely to be a stable
|
| 150 |
+
numerical *specification*.
|
| 151 |
+
|
| 152 |
+
### What the tolerance does NOT permit
|
| 153 |
+
|
| 154 |
+
The tolerance exists **only** to absorb low-precision arithmetic noise. You are responsible for a **faithful
|
| 155 |
+
implementation of the specified computation**. It is not a budget to spend on approximation. The following
|
| 156 |
+
are wrong answers even if they happen to land inside the tolerance at some shape:
|
| 157 |
+
|
| 158 |
+
- changing the algorithm to something that merely *approximates* the spec (dropping terms, truncating a
|
| 159 |
+
series, low-rank or sketched substitutes, skipping a correction term);
|
| 160 |
+
- shortening the computation (fewer iterations/steps than specified, early exit on a heuristic, subsampling
|
| 161 |
+
or striding over the sequence, ignoring positions whose contribution "looks small");
|
| 162 |
+
- computing at a coarser granularity than the spec (sharing a decay, scale, or normaliser across positions
|
| 163 |
+
that the spec gives their own);
|
| 164 |
+
- anything whose error **grows** with sequence length, batch, or head count.
|
| 165 |
+
|
| 166 |
+
A faithful bf16/fp8 kernel's error is *noise*: it stays flat as the problem grows and sits an order of
|
| 167 |
+
magnitude below the gate. An approximation's error is *bias*: it scales with the problem. The graded shapes
|
| 168 |
+
are deliberately large, so the difference shows up.
|
| 169 |
+
|
| 170 |
+
## What's available
|
| 171 |
+
|
| 172 |
+
- **Triton 3.6** (with Gluon), **CUDA C++ via `nvcc`** (`torch.utils.cpp_extension.load` for an inline
|
| 173 |
+
extension), header-only **CUTLASS** at `/opt/cutlass/include`, and the **CuTe DSL**
|
| 174 |
+
(`nvidia-cutlass-dsl`). C++ / CuTe DSL is the encouraged route; Triton is fully supported.
|
| 175 |
+
- `torch` 2.11 (CUDA 12.8) and `einops` for bookkeeping.
|
| 176 |
+
- A GPU with compute capability sm≥90 (Hopper or newer).
|
| 177 |
+
- **No internet access.** `pip install` and cloning repos are blocked. Everything you are permitted to use is
|
| 178 |
+
already installed, and no library implementation of this kernel exists on the machine.
|
| 179 |
+
- Manage any long-running background job (a build, an `ncu`/`nsys` profile) by its **recorded PID** — see
|
| 180 |
+
`/app/CLAUDE.md` and `/app/PROCESS_MANAGEMENT.md`.
|
| 181 |
+
|
| 182 |
+
## How the grading actually runs (so there are no surprises)
|
| 183 |
+
|
| 184 |
+
- **`/app/sta_ragged.py` is the only file that is graded.** The grader imports `sta_ragged_attention` from it and reads nothing
|
| 185 |
+
else from `/app`.
|
| 186 |
+
- **The grader is not on this machine while you work.** It is copied in only after your session ends and it
|
| 187 |
+
carries its **own private copy of the reference** and its own input generator. Editing `/app/reference.py`
|
| 188 |
+
or `/app/measure.py` is allowed — they are yours to experiment with — but it has **no effect whatsoever on
|
| 189 |
+
your score**. Do not spend budget on them.
|
| 190 |
+
- **Every timed repetition uses freshly generated inputs**, and the output of a timed call is itself checked
|
| 191 |
+
against the reference. Caching or memoizing a result and replaying it fails the correctness gate rather
|
| 192 |
+
than producing a fast measurement. Ordinary shape-keyed JIT/autotune caching is fine and is not penalised.
|
| 193 |
+
- **The timed shapes are correctness-checked too.** Being correct only at the small shapes scores **0**.
|
| 194 |
+
- Inputs are random each grade and the graded shapes are not the ones in `measure.py`.
|