KBench / tools /mega_factory /models /fused_layers.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.53 kB
"""One (or a few) complete transformer decoder layers, taking a hidden state in and out.
This is the megakernel problem with the whole-model scaffolding removed: no embedding, no LM head,
no 16-layer schedule to amortise anything over. Just RMSNorm -> QKV -> RoPE -> KV append -> GQA
attention -> output projection -> residual -> RMSNorm -> SwiGLU MLP -> residual, which is about 40
fusable operations, and it must come out of one launch.
`src(build_name, step_name)` renders the reference with task-specific entry-point names.
"""
from model import HELPERS_CORE
TEMPLATE = r'''
def make_weights(cfg, seed=0, device="cuda"):
"""Deterministic 1/sqrt(fan_in)-scaled weights. No checkpoint is shipped or downloaded."""
g = torch.Generator(device=device).manual_seed(seed)
d, ffn, n_q, n_kv, hd = cfg["d"], cfg["ffn"], cfg["n_q"], cfg["n_kv"], cfg["hd"]
def rnd(*shape, fan_in):
return (torch.randn(*shape, device=device, dtype=torch.float32, generator=g)
/ (fan_in ** 0.5)).to(torch.bfloat16)
ones = lambda: torch.ones(d, device=device, dtype=torch.bfloat16)
layers = []
for _ in range(cfg["layers"]):
layers.append(dict(
in_norm=ones(), post_norm=ones(),
q=rnd(n_q * hd, d, fan_in=d), k=rnd(n_kv * hd, d, fan_in=d),
v=rnd(n_kv * hd, d, fan_in=d), o=rnd(d, n_q * hd, fan_in=n_q * hd),
gate=rnd(ffn, d, fan_in=d), up=rnd(ffn, d, fan_in=d), down=rnd(d, ffn, fan_in=ffn)))
return {"layers": layers}
def make_kv(cfg, batch, prefill_len, max_seq, seed=0, device="cuda"):
"""KV cache already holding `prefill_len` tokens. Decode starts at pos = prefill_len."""
g = torch.Generator(device=device).manual_seed(seed + 777)
kv = []
for _ in range(cfg["layers"]):
k = torch.zeros(batch, cfg["n_kv"], max_seq, cfg["hd"], device=device, dtype=torch.bfloat16)
v = torch.zeros_like(k)
k[:, :, :prefill_len] = torch.randn(batch, cfg["n_kv"], prefill_len, cfg["hd"], device=device,
dtype=torch.float32, generator=g).to(torch.bfloat16) * 0.5
v[:, :, :prefill_len] = torch.randn(batch, cfg["n_kv"], prefill_len, cfg["hd"], device=device,
dtype=torch.float32, generator=g).to(torch.bfloat16) * 0.5
kv.append((k, v))
return kv
def make_step_args(cfg, batch, base_pos, seed, n):
"""(x, pos) per call -- a fresh (B, d) bf16 hidden state and the position being appended."""
g = torch.Generator(device="cuda").manual_seed(seed)
return [(torch.randn(batch, cfg["d"], device="cuda", dtype=torch.float32,
generator=g).to(torch.bfloat16), base_pos + i) for i in range(n)]
def {BUILD}(weights, kv_cache, cfg, max_seq_len):
"""UNTIMED setup. Repack weights, build RoPE tables, allocate scratch, launch a daemon, ..."""
dev = weights["layers"][0]["q"].device
cos, sin = _rope_cache(cfg, max_seq_len, dev)
return {"W": weights["layers"], "kv": kv_cache, "cfg": cfg, "cos": cos, "sin": sin}
@torch.no_grad()
def {STEP}(handle, x, pos):
"""Run the layer(s) on one hidden state; append this position's K/V into the cache.
x : (B, d) bf16 the incoming residual stream
pos : int the absolute position being written
returns : (B, d) fp32 the residual stream after the layer(s)
"""
W, kv, cfg = handle["W"], handle["kv"], handle["cfg"]
cos, sin = handle["cos"], handle["sin"]
B = x.shape[0]
n_q, n_kv, hd = cfg["n_q"], cfg["n_kv"], cfg["hd"]
rep = n_q // n_kv
for li, L in enumerate(W):
h = _rms_norm(x, L["in_norm"], cfg["eps"])
q = (h @ L["q"].T).view(B, n_q, 1, hd)
k = (h @ L["k"].T).view(B, n_kv, 1, hd)
v = (h @ L["v"].T).view(B, n_kv, 1, hd)
q = _apply_rope(q, cos, sin, pos)
k = _apply_rope(k, cos, sin, pos)
kc, vc = kv[li]
kc[:, :, pos:pos + 1] = k
vc[:, :, pos:pos + 1] = v
kk = kc[:, :, :pos + 1].repeat_interleave(rep, dim=1)
vv = vc[:, :, :pos + 1].repeat_interleave(rep, dim=1)
att = F.scaled_dot_product_attention(q, kk, vv)
x = x + (att.reshape(B, n_q * hd) @ L["o"].T)
h = _rms_norm(x, L["post_norm"], cfg["eps"])
x = x + ((F.silu(h @ L["gate"].T) * (h @ L["up"].T)) @ L["down"].T)
return x.float()
'''
def src(build_name, step_name):
return HELPERS_CORE + TEMPLATE.replace("{BUILD}", build_name).replace("{STEP}", step_name)