Download tasks/moe/deepseek-node-dispatch-pack/tests/verify_env.py from ZMC2019/KBench: direct link, hf CLI and curl.
- Browser
- Download file 9.19 kB
-
https://huggingface.co/datasets/ZMC2019/KBench/resolve/main/tasks/moe/deepseek-node-dispatch-pack/tests/verify_env.py
- Command line
-
hf download hf://datasets/ZMC2019/KBench/tasks/moe/deepseek-node-dispatch-pack/tests/verify_env.py
-
curl -L -o verify_env.py https://huggingface.co/datasets/ZMC2019/KBench/resolve/main/tasks/moe/deepseek-node-dispatch-pack/tests/verify_env.py
9.19 kB
| """deepseek-node-dispatch-pack verifier — correctness gate + achieved-GB/s SPEED LEADERBOARD (uncapped). | |
| reward = 0 if the submission is incorrect | |
| reward = geomean over graded shapes of GB/s otherwise | |
| GENERATED by _factory/build.py — do not edit here; edit the spec and regenerate. | |
| There is no gold solution and no oracle: the score is an absolute hardware metric, so it is hardware-portable | |
| by construction and nothing has to be vendored, sealed, or re-benchmarked. | |
| CORRECTNESS is a hard gate, checked against an INDEPENDENT (embedded) copy of the reference at every graded | |
| shape including the timed ones, so editing /app/reference.py cannot affect grading and a fast wrong kernel | |
| scores 0. | |
| ANTI-CHEAT on the timing path: every timed rep runs on FRESHLY generated inputs, and the output of the last | |
| timed rep is itself validated against the reference for those exact inputs. A submission that memoizes a | |
| result and replays it fails the gate instead of posting an inflated number. Warm-up runs on a separate | |
| throwaway input set, so ordinary shape-keyed JIT/autotune caching is not penalised. | |
| WORK is attributed by a CANONICAL formula that depends only on the shape, never on the implementation, so all | |
| submissions are credited identically and the ranking is a pure speed ranking. | |
| """ | |
| import importlib.util | |
| import json | |
| import math | |
| import os | |
| import sys | |
| import traceback | |
| import torch | |
| REWARD_DIR = "/logs/verifier" | |
| MODULE_PATH = "/app/dispatch_pack.py" | |
| TOL = 1e-05 | |
| NAMES = ('send_buf', 'src_token', 'node_counts', 'node_offsets') | |
| GRADER_SHAPES = [(32768, 7168, 8, 8, 4, 32), (24576, 7168, 8, 8, 4, 32), (49152, 4096, 8, 8, 4, 32), (32768, 7168, 6, 8, 3, 32), (32768, 5120, 8, 4, 3, 64)] | |
| CORRECT_SHAPES = [(256, 512, 8, 4, 2, 16), (129, 256, 6, 4, 3, 8), (512, 1024, 8, 8, 4, 16), (64, 128, 4, 4, 2, 8)] | |
| sys.path.insert(0, "/app") | |
| def canonical_work(T, H, K, N, M, EPN): | |
| """BYTES attributed to one dispatch pack, from the SHAPE ALONE. | |
| The unavoidable traffic: read the (T, H) bf16 hidden states once, read the (T, K) int32 routing table, | |
| write the (T*M, H) bf16 send buffer and the (T*M,) int32 source map. The membership bitset, the | |
| per-node counters and the prefix sum are tiny and never need to reach HBM. Node-limited routing fixes | |
| the number of copies at exactly M per token, so this is a function of the shape alone. This is a | |
| memory-bound kernel, so the score is achieved bandwidth against this fixed byte count. | |
| """ | |
| return 2 * T * H + 4 * T * K + 2 * T * M * H + 4 * T * M + 4 * (2 * N + 1) | |
| def _ref(x, topk_ids, num_nodes, experts_per_node): | |
| """Deduplicate each token's experts to a node set, then gather node-major. | |
| Correct and simple — it is the exact SPECIFICATION, not a performance target. It materialises a dense | |
| (T, N) boolean membership matrix and lets `nonzero` do the ordering and the ranking, which is exactly | |
| the multi-pass shape a real kernel replaces with one privatised histogram and one gather. | |
| """ | |
| T, K = topk_ids.shape | |
| node = topk_ids.to(torch.int64) // experts_per_node # (T, K) node of every routed slot | |
| member = torch.zeros(T, num_nodes, dtype=torch.bool, device=x.device) | |
| member.scatter_(1, node, True) # DEDUP: token -> set of nodes | |
| pairs = member.t().nonzero() # (R, 2) = [node, token], node-major, token-ascending | |
| src = pairs[:, 1] | |
| send_buf = x[src] # the gather | |
| counts = member.sum(0).to(torch.int32) # rows per node | |
| offsets = torch.cat([torch.zeros(1, dtype=torch.int32, device=x.device), | |
| torch.cumsum(counts, 0).to(torch.int32)]) | |
| return send_buf, src.to(torch.int32), counts, offsets | |
| def _mk(T, H, K, N, M, EPN, seed): | |
| """Hidden states plus a NODE-LIMITED routing table: every token's K experts are distinct and span | |
| EXACTLY M distinct nodes, which is what the node-limited router guarantees and what makes the packed | |
| length T*M a function of the shape alone. | |
| Slot j of a token goes to the (j % M)-th of its M chosen nodes, and takes the (j // M)-th entry of a | |
| random permutation of that node's experts — so the K experts are always distinct. | |
| """ | |
| gen = torch.Generator(device="cuda").manual_seed(seed) | |
| x = torch.randn(T, H, device="cuda", dtype=torch.bfloat16, generator=gen) | |
| nodes = torch.rand(T, N, device="cuda", generator=gen).argsort(dim=-1)[:, :M] # (T, M) distinct | |
| perm = torch.rand(T, M, EPN, device="cuda", generator=gen).argsort(dim=-1) # (T, M, EPN) | |
| j = torch.arange(K, device="cuda") | |
| m, r = j % M, j // M | |
| sel_node = nodes[:, m] # (T, K) | |
| sel_off = perm[:, m, r] # (T, K) | |
| topk_ids = (sel_node * EPN + sel_off).to(torch.int32) | |
| del nodes, perm, sel_node, sel_off | |
| return x, topk_ids.contiguous(), N, EPN | |
| def _check(out, ref): | |
| """-> (ok, value, msg). value = MAX relative error across the returned tuple.""" | |
| if out is None or len(out) != len(NAMES): | |
| return False, 1.0, f"expected a {len(NAMES)}-tuple {NAMES}" | |
| per = [] | |
| for n, a, b in zip(NAMES, out, ref): | |
| if a is None or tuple(a.shape) != tuple(b.shape): | |
| return False, 1.0, f"{n} bad shape" | |
| if b.dtype in (torch.int8, torch.int16, torch.int32, torch.int64, torch.uint8, torch.bool): | |
| # exact: .float() is lossy above 2**24 and would let distinct large ids compare equal | |
| bad = int((a != b).sum()) | |
| if bad: | |
| return False, 1.0, f"{n}: {bad} elements differ" | |
| continue | |
| per.append((n, float((a.float() - b.float()).norm() / (b.float().norm() + 1e-12)))) | |
| if not per: | |
| return True, 0.0, "all integer outputs exact" | |
| wn, wv = max(per, key=lambda x: x[1]) | |
| return wv <= TOL, wv, f"worst {wn} {wv:.2e}" | |
| def _bench_fresh(fn, mkargs, reps=5, warm=3): | |
| """Time `fn` on FRESH inputs every rep -> (min_seconds, timed_ok). See the module docstring.""" | |
| wargs = mkargs(0) | |
| for _ in range(warm): | |
| fn(*wargs) | |
| torch.cuda.synchronize() | |
| del wargs | |
| torch.cuda.empty_cache() | |
| best, timed_ok = float("inf"), True | |
| for i in range(reps): | |
| args = mkargs(10_000 + i) | |
| s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True) | |
| s.record() | |
| out = fn(*args) | |
| e.record() | |
| torch.cuda.synchronize() | |
| best = min(best, s.elapsed_time(e)) | |
| if i == reps - 1: | |
| timed_ok = _check(out, _ref(*args))[0] | |
| del args, out | |
| torch.cuda.empty_cache() | |
| return best / 1e3, timed_ok | |
| def _geomean(xs): | |
| return math.exp(sum(math.log(max(v, 1e-9)) for v in xs) / len(xs)) if xs else 0.0 | |
| def main(): | |
| details, correct_gate, geo = {}, False, 0.0 | |
| try: | |
| spec = importlib.util.spec_from_file_location("submission", MODULE_PATH) | |
| m = importlib.util.module_from_spec(spec) | |
| spec.loader.exec_module(m) | |
| fn = m.node_dispatch_pack | |
| corr_ok, msg = True, "" | |
| for i, shp in enumerate(CORRECT_SHAPES): | |
| args = _mk(*shp, seed=10 + i) | |
| ok, val, m_ = _check(fn(*args), _ref(*args)) | |
| if not ok: | |
| corr_ok, msg = False, f"cfg{i} {shp} {m_}" | |
| break | |
| del args | |
| torch.cuda.empty_cache() | |
| details["correct_msg"] = msg or "all correctness shapes pass" | |
| vals, per_shape, perf_ok = [], [], corr_ok | |
| for i, shp in enumerate(GRADER_SHAPES): | |
| args = _mk(*shp, seed=100 + i) | |
| ok, val, m_ = _check(fn(*args), _ref(*args)) | |
| if not ok: | |
| perf_ok = False | |
| del args | |
| torch.cuda.empty_cache() | |
| t, timed_ok = _bench_fresh(fn, lambda s, _p=shp: _mk(*_p, seed=s)) | |
| if not timed_ok: | |
| perf_ok = False | |
| v = canonical_work(*shp) / t / 2**30 if t > 0 else 0.0 | |
| vals.append(v) | |
| per_shape.append({"shape": list(shp), "gbps": round(v, 3), "ms": round(t * 1e3, 3), | |
| "check": m_, "timed_ok": timed_ok}) | |
| geo = _geomean(vals) | |
| details.update(per_shape=per_shape, geomean=round(geo, 4), perf_size_ok=perf_ok) | |
| correct_gate = corr_ok and perf_ok | |
| except Exception as e: | |
| details["error"] = f"{e.__class__.__name__}: {e}"[:220] | |
| details["trace"] = traceback.format_exc()[-800:] | |
| reward = round(geo, 4) if correct_gate else 0.0 | |
| os.makedirs(REWARD_DIR, exist_ok=True) | |
| json.dump({"reward": reward, "correct": 1.0 if correct_gate else 0.0, | |
| "geomean": round(geo, 4), "metric": "GB/s (geomean over graded shapes)"}, | |
| open(f"{REWARD_DIR}/reward.json", "w"), indent=2) | |
| open(f"{REWARD_DIR}/reward.txt", "w").write(str(reward)) | |
| json.dump(details, open(f"{REWARD_DIR}/details.json", "w"), indent=2, default=str) | |
| print("reward:", reward, "GB/s | correct:", 1.0 if correct_gate else 0.0) | |
| main() | |