ZMC2019's picture
Reorganise: group 313 tasks into 17 families under tasks/, generators under tools/ (part 10)
0f775e2 verified
Raw
History Blame Contribute Delete
7.53 kB
"""MegaSpec — everything that varies between megakernel tasks.
The megakernel family cannot use `_factory/spec.py`: those tasks grade ONE pure function over shape
tuples, whereas these grade a STATEFUL, multi-step workload under measured fusion gates with a
throughput reward.
Two sub-families share this spec and this builder:
* `family="e1"` — whole-model decode megakernels. Reward is tokens/s; the gates are correctness,
kernels-per-step and dominant-kernel share, and the kernel-count gate is what makes it a megakernel
task rather than a speed task.
* `family="e2"` — enabling primitives (a device-wide barrier, an instruction interpreter, a fused
layer, a warp-specialised GEMV...). These are NOT whole models, so the kernels-per-*step* gate is
not automatically the right thing to grade; each e2 spec sets its own limits and must justify them
in `gates_md`.
Numbers below that look arbitrary are measured — see CALIBRATION.md.
"""
from dataclasses import dataclass, field
@dataclass
class MegaSpec:
# ---- identity ---------------------------------------------------------------------------------
name: str
title: str
blurb: str
keywords: list = field(default_factory=list)
family: str = "e1" # "e1" whole-model decode | "e2" enabling primitive
# ---- architecture -----------------------------------------------------------------------------
# wdtype: "bf16" | "fp8" | "int4" | "nvfp4". Every quantised form ships weights ALREADY quantised
# with their scales and the reference dequantises those exact bytes (see CALIBRATION.md §6).
cfg: dict = field(default_factory=dict)
# Reference/fixture source embedded verbatim into both environment/reference.py and the private
# grader. Empty -> the shared Llama-shaped decoder in model.py.
model_src: str = ""
# ---- decode regime ----------------------------------------------------------------------------
batch: int = 1 # small by design: this family lives in the latency regime
prefill_len: int = 2048 # KV already holds this many tokens when the timed loop starts
max_seq: int = 4096
decode_steps: int = 32 # timed steps per rep
correct_steps: int = 8 # steps compared against the reference
prof_steps: int = 4 # steps profiled for the kernel-count gate
# ---- gates ------------------------------------------------------------------------------------
tol: float = 3e-2 # full-output RELATIVE error. NOT top-k agreement: with random
# weights logits are near-uniform, top-1 ties flip on noise and a
# correct kernel fails (measured top1 0.79-0.92). relerr is stable.
max_kernels_per_step: float = 8.0
min_dominant_share: float = 0.90
# ---- reward -----------------------------------------------------------------------------------
reward_metric: str = "tokens/s"
reward_work: float = 0.0 # numerator per step; 0 -> `batch` (one token per sequence per step)
# ---- entry points -----------------------------------------------------------------------------
entry_build: str = "build_model"
entry_step: str = "decode_step"
step_sig: str = "handle, token_ids, pos"
step_doc: str = ("One decode step for the whole batch; append this position's K/V into the cache."
"\n\n token_ids : (B,) int64 pos : int, absolute position being written"
"\n returns : (B, vocab) logits\n ")
step_ret: str = "logits"
unfused_kernels: int = 0 # measured kernel launches/call for the eager reference, if known
arg_doc: str = ("weights : dict from the reference's make_weights (see /app/reference.py)"
"\n kv_cache : list of (k, v) per layer, each (B, n_kv, max_seq_len, hd) bf16,"
" prefilled")
# ---- roofline ---------------------------------------------------------------------------------
bytes_per_step: float = 0.0 # override; 0 -> weight_bytes() + kv_bytes() (Llama-shaped only)
floor_us_override: float = 0.0 # override the roofline entirely (compute-bound tasks)
# ---- prose ------------------------------------------------------------------------------------
intro_md: str = ""
spec_md: str = ""
contract_md: str = ""
regime_md: str = ""
perf_md: str = ""
precision_md: str = ""
correctness_md: str = ""
gates_md: str = "" # REQUIRED for family e2: why these gate values are the right ones
faithfulness_md: str = ""
# ---- environment ------------------------------------------------------------------------------
base_image: str = "pytorch/pytorch:2.11.0-cuda12.8-cudnn9-devel"
pip_extra: str = "einops nvidia-cutlass-dsl"
module: str = "megakernel.py"
gpus: int = 1
agent_timeout_sec: float = 14400.0
verifier_timeout_sec: float = 2700.0
memory_mb: int = 65536
ELT = {"bf16": 2, "fp8": 1, "int4": 0.5, "nvfp4": 0.5}
def weight_bytes(self):
"""Bytes of weight read per decode step -- the roofline. lm_head is read in full at bs=1.
Only meaningful for the plain Llama-shaped configs; anything else (MoE, hybrid, primitives)
sets `bytes_per_step` explicitly."""
c = self.cfg
d, ffn, n_q, n_kv, hd = c["d"], c["ffn"], c["n_q"], c["n_kv"], c["hd"]
per_layer = n_q * hd * d + 2 * n_kv * hd * d + d * n_q * hd + 3 * ffn * d
elt = self.ELT[c["wdtype"]]
return (c["layers"] * per_layer + c["vocab"] * d) * elt
def kv_bytes(self):
"""Bytes of KV read per decode step at the deepest position."""
c = self.cfg
return (2 * self.batch * c["layers"] * c["n_kv"]
* (self.prefill_len + self.decode_steps) * c["hd"] * 2)
def total_bytes(self):
if self.bytes_per_step:
return float(self.bytes_per_step)
return self.weight_bytes() + self.kv_bytes()
def floor_us(self, hbm_bw=4.8e12):
if self.floor_us_override:
return float(self.floor_us_override)
return self.total_bytes() / hbm_bw * 1e6
def work_per_step(self):
return self.reward_work or float(self.batch)
def validate(self):
assert self.name and self.cfg, "name/cfg required"
assert self.family in ("e1", "e2"), self.family
assert "wdtype" in self.cfg and self.cfg["wdtype"] in self.ELT, self.cfg.get("wdtype")
if self.family == "e1":
for k in ("layers", "d", "n_q", "n_kv", "hd", "vocab", "eps", "theta"):
assert k in self.cfg, f"cfg missing {k}"
assert self.cfg["n_q"] % self.cfg["n_kv"] == 0, "n_q must be a multiple of n_kv"
assert self.batch <= 8, "whole-model megakernels are a SMALL-batch family by construction"
assert self.prefill_len + self.decode_steps * max(1, int(self.cfg.get("tokens_per_step", 1))) \
<= self.max_seq, "decode would overrun max_seq"
else:
assert self.gates_md.strip(), (
"family e2 must justify its gates in gates_md -- the kernels-per-step gate is not "
"automatically the right contract for a primitive")
# the task is only meaningful if there is headroom to fuse into
assert self.floor_us() > 50, f"roofline {self.floor_us():.0f}us too small to be measurable"
return self