Download tasks/megakernel/instruction-interpreter-dispatch/environment/reference.py from ZMC2019/KBench: direct link, hf CLI and curl.
- Browser
- Download file 4.31 kB
-
https://huggingface.co/datasets/ZMC2019/KBench/resolve/main/tasks/megakernel/instruction-interpreter-dispatch/environment/reference.py
- Command line
-
hf download hf://datasets/ZMC2019/KBench/tasks/megakernel/instruction-interpreter-dispatch/environment/reference.py
-
curl -L -o reference.py https://huggingface.co/datasets/ZMC2019/KBench/resolve/main/tasks/megakernel/instruction-interpreter-dispatch/environment/reference.py
4.31 kB
| """Reference implementation — the CORRECTNESS SPEC for `instruction-interpreter-dispatch`. | |
| Correct, deliberately unfused, and slow. Its speed has no bearing on your score, which is an | |
| absolute instructions/s number. GENERATED by _mega_factory/build.py. | |
| """ | |
| import torch | |
| import torch.nn.functional as F | |
| def make_step_args(cfg, batch, base_pos, seed, n): | |
| """Arguments passed to each step, after the handle. Default: (token_ids, pos).""" | |
| g = torch.Generator(device="cuda").manual_seed(seed) | |
| return [(torch.randint(0, cfg["vocab"], (batch,), device="cuda", generator=g), base_pos + i) | |
| for i in range(n)] | |
| def compare(got, exp): | |
| """Relative error (Frobenius) used by the correctness gate. Tuples compare worst-elementwise.""" | |
| if isinstance(exp, (tuple, list)): | |
| return max(compare(g, e) for g, e in zip(got, exp)) | |
| a, b = got.float(), exp.float() | |
| return ((a - b).norm() / b.norm().clamp(min=1e-9)).item() | |
| N_OPS = 4 # 0 MATVEC, 1 ADD, 2 RMSNORM, 3 GATE | |
| def make_weights(cfg, seed=0, device="cuda"): | |
| """A bank of `n_bank` (d, d) matrices -- the only thing MATVEC instructions can reference.""" | |
| g = torch.Generator(device=device).manual_seed(seed) | |
| d, nb = cfg["d"], cfg["n_bank"] | |
| w = torch.randn(nb, d, d, device=device, dtype=torch.float32, generator=g) / (d ** 0.5) | |
| return {"bank": w.to(torch.bfloat16)} | |
| def make_kv(cfg, batch, prefill_len, max_seq, seed=0, device="cuda"): | |
| """No KV cache in this task.""" | |
| return [] | |
| def make_step_args(cfg, batch, base_pos, seed, n): | |
| """(x0, program) per call. A fresh random SSA program every call -- it cannot be precompiled. | |
| program is (n_instr, 4) int32: (op, src0, src1, bank). Instruction i writes slot i+1 and reads | |
| slots drawn uniformly from [max(0, i+1-window) .. i], so the program is always well formed and | |
| always has a valid topological order (its own order), but never a purely serial one.""" | |
| g = torch.Generator(device="cuda").manual_seed(seed) | |
| I, d, nb, W = cfg["n_instr"], cfg["d"], cfg["n_bank"], cfg["window"] | |
| i_idx = torch.arange(I, device="cuda", dtype=torch.int64) | |
| lo = (i_idx + 1 - W).clamp(min=0) | |
| cnt = (i_idx + 1 - lo).to(torch.float32) | |
| cuts = torch.tensor([0.50, 0.66, 0.88], device="cuda") | |
| out = [] | |
| for _ in range(n): | |
| x0 = torch.randn(d, device="cuda", dtype=torch.float32, generator=g) | |
| u = torch.rand(I, 4, device="cuda", generator=g) | |
| op = torch.bucketize(u[:, 0], cuts) | |
| s0 = lo + (u[:, 1] * cnt).to(torch.int64) | |
| s1 = lo + (u[:, 2] * cnt).to(torch.int64) | |
| bk = (u[:, 3] * nb).to(torch.int64) | |
| prog = torch.stack([op, s0, s1, bk], dim=1).to(torch.int32).contiguous() | |
| out.append((x0, prog)) | |
| return out | |
| def build_interpreter(weights, kv_cache, cfg, max_seq_len): | |
| """UNTIMED setup. Repack the bank, allocate the slot arena and the queue, launch a daemon, ...""" | |
| return {"bank": weights["bank"], "cfg": cfg} | |
| def run_program(handle, x0, program): | |
| """Execute the whole program and return every slot. | |
| x0 : (d,) fp32 slot 0 | |
| program : (n_instr, 4) int32 (op, src0, src1, bank) per instruction | |
| returns : (n_instr + 1, d) fp32 slot 0 is x0, slot i+1 is instruction i's result | |
| """ | |
| bank, cfg = handle["bank"], handle["cfg"] | |
| I, d, eps = cfg["n_instr"], cfg["d"], cfg["eps"] | |
| prog = program.to("cpu") # the reference walks the program on the host | |
| slots = torch.empty(I + 1, d, device=x0.device, dtype=torch.float32) | |
| slots[0] = x0 | |
| for i in range(I): | |
| op, a, b, w = (int(t) for t in prog[i]) | |
| if op == 0: # MATVEC : bank[w] @ slot[a] | |
| y = torch.matmul(bank[w], slots[a].to(torch.bfloat16)).float() | |
| elif op == 1: # ADD : (slot[a] + slot[b]) * 2**-0.5 | |
| y = (slots[a] + slots[b]) * 0.70710678 | |
| elif op == 2: # RMSNORM: slot[a] / rms(slot[a]) | |
| y = slots[a] * torch.rsqrt(slots[a].pow(2).mean() + eps) | |
| else: # GATE : 1.8 * slot[a] * sigmoid(slot[b]) | |
| y = 1.8 * slots[a] * torch.sigmoid(slots[b]) | |
| slots[i + 1] = y | |
| return slots | |