KBench / tools /mega_factory /models /instr_interp.py
ZMC2019's picture
Reorganise: group 313 tasks into 17 families under tasks/, generators under tools/ (part 10)
0f775e2 verified
Raw
History Blame Contribute Delete
4.44 kB
"""An MPK-style instruction interpreter: a task graph, executed by one persistent kernel.
Mirage / MPK style megakernels do not hard-code the model. They compile it into a stream of *tasks*
-- (opcode, operand slots, dependency count) -- and a single persistent kernel pops tasks off a queue,
runs them, and decrements the dependency counters of their successors. The model becomes data.
This task is that executor, isolated. The program arrives as a GPU int32 tensor and is DIFFERENT ON
EVERY CALL, so it cannot be specialised away at build time: the kernel has to interpret it, discover
the dependency structure at run time, and schedule around it.
The program is in SSA form -- instruction `i` writes slot `i+1` and reads only slots `<= i` -- so the
dependencies are pure data flow with no write-after-read hazards, and the graph has real width: source
slots are drawn from a window of the 16 most recent slots, which leaves roughly 8x of instruction-level
parallelism for a scheduler to exploit and none at all for an in-order interpreter.
"""
BODY = r'''
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}
@torch.no_grad()
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
'''
MODEL_SRC = BODY