foundry4-synth / synth4.py
Akahsizrr's picture
Upload synth4.py with huggingface_hub
2f3e08f verified
Raw History Blame Contribute Delete
35.6 kB
"""synth4.py — curated, *verified* kernel-optimization episode generator.
Every episode is real: task spec -> a ladder of genuinely different
kernel variants (mutated tile sizes, vector widths, strategies) -> each
graded on-GPU for correctness + measured ms -> rendered in the corpus
episode format with real observation records.
The point: the model learns hill-climbing semantics from honest
measurements (this variant compiled, was correct, ran at X ms) and the
judge head gets real improvement labels instead of LM-only signal.
Templates produce diverse code: sampled variable names, block sizes,
vector widths, warp counts, comment styles, and code order — this is
pretraining diversity, not a fixed answer key.
Worker model: grading runs `synth4.py --grade` in a subprocess per
variant (bad triton can poison the CUDA context — same discipline as
_hb_worker.py).
python3 synth4.py --out ~/foundry4_data/synth --episodes 400
"""
import argparse
import json
import os
import random
import subprocess
import sys
import tempfile
LT = chr(60) + chr(124)
GT = chr(62)
M_PROMPT = LT + "prompt" + GT
M_KERNEL = LT + "kernel" + GT
M_OBS = LT + "obs" + GT
M_EOS = LT + "eos" + GT
M_DONE = LT + "done" + GT
# name pools for code diversity
IDX = ["pid", "bid", "off0", "pidx"]
ROWS = ["row", "r", "i0", "m0"]
COLS = ["col", "c", "j0", "n0"]
BLK = ["BLOCK", "BS", "TILE", "NB"]
def R(rng, pool):
return rng.choice(pool)
# ---------------------------------------------------------------------------
# task families: (spec, ref torch expr, variant ladder of code templates)
# each variant: {"desc": str, "code": str} — code defines run(*ins)
# ---------------------------------------------------------------------------
def fam_elementwise(rng):
"""y = silu(x)*u style fused pointwise — naive -> vectorized -> tuned."""
M = rng.choice([4096, 8192, 16384])
N = rng.choice([512, 1024, 2048])
spec = {"name": "swiglu_silu", "inputs": [("g", (M, 2 * N))],
"ref": f"torch.nn.functional.silu(g[:, :{N}]) * g[:, {N}:]",
"shapes": {"g": [M, 2 * N]}, "dtype": "bf16", "tol": 2e-2,
"sig": "def run(g) -> torch.Tensor"}
i, b = R(rng, IDX), R(rng, BLK)
vs = []
vs.append({"desc": "scalar one-elem-per-thread",
"code": f"""
import torch, triton, triton.language as tl
@triton.jit
def _k(g, o, N, T, {b}: tl.constexpr):
{i} = tl.program_id(0) * {b} + tl.arange(0, {b})
m = {i} < T
r = {i} // N
c = {i} % N
a = tl.load(g + r * (2 * N) + c, mask=m, other=0.0)
u = tl.load(g + r * (2 * N) + N + c, mask=m, other=0.0)
a = a.to(tl.float32); u = u.to(tl.float32)
y = (a * tl.sigmoid(a)) * u
tl.store(o + {i}, y.to(o.dtype.element_ty), mask=m)
def run(g):
M, W = g.shape; N = W // 2; T = M * N
o = torch.empty(M, N, device=g.device, dtype=g.dtype)
_k[(triton.cdiv(T, 1024),)](g, o, N, T, 1024)
return o
"""})
for bs, vec in [(256, 1), (1024, 1), (512, 2), (2048, 1)]:
vs.append({"desc": f"block {bs} vec hint {vec}",
"code": f"""
import torch, triton, triton.language as tl
@triton.jit
def _k(g, o, N, T, {b}: tl.constexpr):
{i} = tl.program_id(0) * {b} + tl.arange(0, {b})
m = {i} < T
a = tl.load(g + ({i} // N) * (2 * N) + ({i} % N), mask=m, other=0.)
u = tl.load(g + ({i} // N) * (2 * N) + N + ({i} % N), mask=m, other=0.)
y = (a.to(tl.float32) * tl.sigmoid(a.to(tl.float32))) * u.to(tl.float32)
tl.store(o + {i}, y.to(o.dtype.element_ty), mask=m)
def run(g):
M, W = g.shape; N = W // 2; T = M * N
o = torch.empty(M, N, device=g.device, dtype=g.dtype)
_k[(triton.cdiv(T, {bs}),)](g, o, N, T, {bs}, num_warps={rng.choice([4, 8])})
return o
"""})
rn_, cn_ = R(rng, ROWS), R(rng, COLS)
vs.append({"desc": "2d grid over rows",
"code": f"""
import torch, triton, triton.language as tl
@triton.jit
def _k(g, o, M, N, {b}: tl.constexpr):
{rn_} = tl.program_id(0)
{cn_} = tl.program_id(1) * {b} + tl.arange(0, {b})
m = {cn_} < N
p = g + {rn_} * (2 * N) + {cn_}
a = tl.load(p, mask=m, other=0.); u = tl.load(p + N, mask=m, other=0.)
a = a.to(tl.float32); u = u.to(tl.float32)
y = a * tl.sigmoid(a) * u
tl.store(o + {rn_} * N + {cn_}, y.to(o.dtype.element_ty), mask=m)
def run(g):
M, W = g.shape; N = W // 2
o = torch.empty(M, N, device=g.device, dtype=g.dtype)
_k[(M, triton.cdiv(N, 512))](g, o, M, N, 512, num_warps=4)
return o
"""})
return spec, vs
def fam_softmax(rng):
R_, C = rng.choice([2048, 4096, 8192]), rng.choice([2048, 4096, 8192])
NB = 1 << (C - 1).bit_length()
spec = {"name": "softmax_row", "inputs": [("x", (R_, C))],
"ref": "torch.softmax(x, -1)",
"shapes": {"x": [R_, C]}, "dtype": "bf16", "tol": 2e-2,
"sig": "def run(x) -> torch.Tensor"}
r, c, b = R(rng, ROWS), R(rng, COLS), R(rng, BLK)
vs = [{"desc": "three-pass row softmax", "code": f"""
import torch, triton, triton.language as tl
@triton.jit
def _k(x, o, C, {b}: tl.constexpr):
{r} = tl.program_id(0)
{c} = tl.arange(0, {b})
m = {c} < C
v = tl.load(x + {r} * C + {c}, mask=m, other=float('-inf')).to(tl.float32)
mx = tl.max(v, 0)
e = tl.exp(v - mx)
e = tl.where(m, e, 0.0)
s = tl.sum(e, 0)
tl.store(o + {r} * C + {c}, (e / s).to(o.dtype.element_ty), mask=m)
def run(x):
R, C = x.shape
o = torch.empty_like(x)
_k[(R,)](x, o, C, {NB})
return o
"""}]
vs.append({"desc": "exp2 single-pass online", "code": f"""
import torch, triton, triton.language as tl
@triton.jit
def _k(x, o, C, {b}: tl.constexpr):
{r} = tl.program_id(0)
{c} = tl.arange(0, {b})
m = {c} < C
v = tl.load(x + {r} * C + {c}, mask=m, other=float('-inf')).to(tl.float32)
mx = tl.max(v, 0)
e = tl.exp2((v - mx) * 1.4426950408889634)
e = tl.where(m, e, 0.0)
s = tl.sum(e, 0)
tl.store(o + {r} * C + {c}, (e / s).to(o.dtype.element_ty), mask=m)
def run(x):
R, C = x.shape
o = torch.empty_like(x)
_k[(R,)](x, o, C, {NB}, num_warps={rng.choice([4, 8, 16])})
return o
"""})
return spec, vs
def fam_rmsnorm(rng):
R_, C = rng.choice([1024, 2048, 4096]), rng.choice([2048, 4096, 8192])
NB = 1 << (C - 1).bit_length()
spec = {"name": "rmsnorm_row", "inputs": [("x", (R_, C)), ("w", (C,))],
"ref": "x * torch.rsqrt(x.pow(2).mean(-1,keepdim=True)+1e-6) * w",
"shapes": {"x": [R_, C], "w": [C]}, "dtype": "bf16",
"tol": 2e-2, "sig": "def run(x, w) -> torch.Tensor"}
r, c, b = R(rng, ROWS), R(rng, COLS), R(rng, BLK)
vs = [{"desc": "fused single-pass rmsnorm", "code": f"""
import torch, triton, triton.language as tl
@triton.jit
def _k(x, w, o, C, {b}: tl.constexpr):
{r} = tl.program_id(0)
{c} = tl.arange(0, {b})
m = {c} < C
v = tl.load(x + {r} * C + {c}, mask=m, other=0.).to(tl.float32)
ms = tl.sum(v * v, 0) / C
inv = 1.0 / tl.sqrt(ms + 1e-6)
wt = tl.load(w + {c}, mask=m, other=0.).to(tl.float32)
tl.store(o + {r} * C + {c}, (v * inv * wt).to(o.dtype.element_ty), mask=m)
def run(x, w):
R, C = x.shape
o = torch.empty_like(x)
_k[(R,)](x, w, o, C, {NB})
return o
"""}]
return spec, vs
def fam_gemm(rng):
M = rng.choice([1024, 2048, 4096])
N = rng.choice([1024, 2048, 4096])
K = rng.choice([1024, 2048, 4096])
spec = {"name": "gemm_nn", "inputs": [("a", (M, K)), ("b", (K, N))],
"ref": "a @ b", "shapes": {"a": [M, K], "b": [K, N]},
"dtype": "bf16", "tol": 3e-2, "sig": "def run(a, b) -> torch.Tensor"}
pm, pn, pk, gs = (R(rng, IDX + ["pm"]), R(rng, IDX + ["pn"]),
"kk", "GROUP")
vs = [{"desc": "naive tiled one-block-row", "code": f"""
import torch, triton, triton.language as tl
@triton.jit
def _k(a, b, c, M, N, K, BM: tl.constexpr, BN: tl.constexpr,
BK: tl.constexpr):
{pm} = tl.program_id(0); {pn} = tl.program_id(1)
rm = {pm} * BM + tl.arange(0, BM)
rn = {pn} * BN + tl.arange(0, BN)
acc = tl.zeros((BM, BN), dtype=tl.float32)
for k0 in range(0, K, BK):
rk = k0 + tl.arange(0, BK)
ta = tl.load(a + rm[:, None] * K + rk[None, :],
mask=(rm[:, None] < M) & (rk[None, :] < K), other=0.)
tb = tl.load(b + rk[:, None] * N + rn[None, :],
mask=(rk[:, None] < K) & (rn[None, :] < N), other=0.)
acc += tl.dot(ta, tb)
tl.store(c + rm[:, None] * N + rn[None, :],
acc.to(c.dtype.element_ty),
mask=(rm[:, None] < M) & (rn[None, :] < N))
def run(a, b):
M, K = a.shape; K2, N = b.shape
c = torch.empty(M, N, device=a.device, dtype=a.dtype)
_k[(triton.cdiv(M, 64), triton.cdiv(N, 64))](a, b, c, M, N, K,
64, 64, 32)
return c
"""}]
for bm, bn, bk, gsz, w, s in [(128, 128, 64, 8, 8, 3),
(128, 256, 64, 8, 8, 4),
(64, 128, 64, 4, 4, 3)]:
vs.append({"desc": f"grouped raster BM{bm} BN{bn} BK{bk}",
"code": f"""
import torch, triton, triton.language as tl
@triton.jit
def _k(a, b, c, M, N, K, BM: tl.constexpr, BN: tl.constexpr,
BK: tl.constexpr, {gs}: tl.constexpr):
pid = tl.program_id(0)
nm = tl.cdiv(M, BM); nn = tl.cdiv(N, BN)
ng = {gs} * nn
gid = pid // ng; first = gid * {gs}; gsz = min(nm - first, {gs})
{pm} = first + (pid % gsz); {pn} = (pid % ng) // gsz
rm = {pm} * BM + tl.arange(0, BM); rn = {pn} * BN + tl.arange(0, BN)
acc = tl.zeros((BM, BN), dtype=tl.float32)
for k0 in range(0, K, BK):
rk = k0 + tl.arange(0, BK)
ta = tl.load(a + rm[:, None] * K + rk[None, :],
mask=(rm[:, None] < M) & (rk[None, :] < K), other=0.)
tb = tl.load(b + rk[:, None] * N + rn[None, :],
mask=(rk[:, None] < K) & (rn[None, :] < N), other=0.)
acc += tl.dot(ta, tb)
tl.store(c + rm[:, None] * N + rn[None, :],
acc.to(c.dtype.element_ty),
mask=(rm[:, None] < M) & (rn[None, :] < N))
def run(a, b):
M, K = a.shape; K2, N = b.shape
c = torch.empty(M, N, device=a.device, dtype=a.dtype)
grid = (triton.cdiv(M, {bm}) * triton.cdiv(N, {bn}),)
_k[grid](a, b, c, M, N, K, {bm}, {bn}, {bk}, {gsz},
num_warps={w}, num_stages={s})
return c
"""})
return spec, vs
def fam_reduction(rng):
R_, C = rng.choice([1024, 2048, 4096]), rng.choice([4096, 8192, 16384])
spec = {"name": "rowsum", "inputs": [("x", (R_, C))],
"ref": "x.sum(-1)", "shapes": {"x": [R_, C]},
"dtype": "bf16", "tol": 2e-2, "sig": "def run(x) -> torch.Tensor"}
r, c, b = R(rng, ROWS), R(rng, COLS), R(rng, BLK)
vs = [{"desc": "two-pass: block reduce + final", "code": f"""
import torch, triton, triton.language as tl
@triton.jit
def _k(x, part, R, C, {b}: tl.constexpr):
{r} = tl.program_id(0); {c} = tl.program_id(1)
offs = {c} * {b} + tl.arange(0, {b})
m = offs < C
v = tl.load(x + {r} * C + offs, mask=m, other=0.).to(tl.float32)
tl.store(part + {r} * tl.num_programs(1) + {c}, tl.sum(v, 0))
@triton.jit
def _f(part, o, NP, {b}: tl.constexpr):
{r} = tl.program_id(0)
offs = tl.arange(0, {b})
m = offs < NP
v = tl.load(part + {r} * NP + offs, mask=m, other=0.)
tl.store(o + {r}, tl.sum(v, 0))
def run(x):
R, C = x.shape
NP = triton.cdiv(C, 1024)
part = torch.empty(R, NP, device=x.device, dtype=torch.float32)
_k[(R, NP)](x, part, R, C, 1024)
o = torch.empty(R, device=x.device, dtype=torch.float32)
_f[(R,)](part, o, NP, 1024)
return o.to(x.dtype)
"""}]
return spec, vs
def fam_conv1d(rng):
B_, C_, L = rng.choice([4, 8]), rng.choice([128, 256]), 8192
K_ = 4
spec = {"name": "conv1d_causal_dw",
"inputs": [("x", (B_, C_, L)), ("w", (C_, 1, K_))],
"ref": ("torch.nn.functional.conv1d(x, w, groups=x.size(1),"
" padding=w.size(-1)-1)[..., :x.size(-1)]"),
"shapes": {"x": [B_, C_, L], "w": [C_, 1, K_]},
"dtype": "bf16", "tol": 2e-2,
"sig": "def run(x, w) -> torch.Tensor"}
bk_ = R(rng, BLK)
vs = [{"desc": "direct causal depthwise conv", "code": f"""
import torch, triton, triton.language as tl
@triton.jit
def _k(x, w, o, C, L, {bk_}: tl.constexpr):
bc = tl.program_id(0)
pid_t = tl.program_id(1)
b_i = bc // C; c_i = bc % C
t = pid_t * {bk_} + tl.arange(0, {bk_})
m = t < L
acc = tl.zeros(({bk_},), dtype=tl.float32)
for kk in tl.static_range(4):
tt = t - (3 - kk)
mv = (tt >= 0) & m
xv = tl.load(x + b_i * C * L + c_i * L + tt, mask=mv, other=0.)
wv = tl.load(w + c_i * 4 + kk)
acc += xv.to(tl.float32) * wv.to(tl.float32)
tl.store(o + b_i * C * L + c_i * L + t, acc.to(o.dtype.element_ty),
mask=m)
def run(x, w):
B, C, L = x.shape
o = torch.empty_like(x)
_k[(B * C, triton.cdiv(L, 512))](x, w, o, C, L, 512)
return o
"""}]
return spec, vs
def fam_cumsum(rng):
R_, C = rng.choice([256, 512]), rng.choice([8192, 16384])
spec = {"name": "cumsum_row", "inputs": [("x", (R_, C))],
"ref": "x.float().cumsum(-1)", "shapes": {"x": [R_, C]},
"dtype": "bf16", "tol": 2e-2, "sig": "def run(x) -> torch.Tensor"}
rn_ = R(rng, ROWS)
vs = [{"desc": "sequential-in-block scan", "code": f"""
import torch, triton, triton.language as tl
@triton.jit
def _k(x, o, C, BLK: tl.constexpr):
{rn_} = tl.program_id(0)
acc = 0.0
for c0 in range(0, C, BLK):
offs = c0 + tl.arange(0, BLK)
m = offs < C
v = tl.load(x + {rn_} * C + offs, mask=m, other=0.).to(tl.float32)
cs = tl.cumsum(v, 0) + acc
acc += tl.sum(v, 0)
tl.store(o + {rn_} * C + offs, cs.to(o.dtype.element_ty),
mask=m)
def run(x):
R, C = x.shape
o = torch.empty_like(x)
_k[(R,)](x, o, C, 2048)
return o
"""}]
return spec, vs
def fam_layernorm(rng):
R_, C = rng.choice([512, 1024, 2048]), rng.choice([2048, 4096])
NB = 1 << (C - 1).bit_length()
spec = {"name": "layernorm_row",
"inputs": [("x", (R_, C)), ("w", (C,)), ("b", (C,))],
"ref": ("(x - x.mean(-1,keepdim=True)) / "
"(x.var(-1,unbiased=False,keepdim=True)+1e-5).sqrt() "
"* w + b"),
"shapes": {"x": [R_, C], "w": [C], "b": [C]}, "dtype": "bf16",
"tol": 3e-2, "sig": "def run(x, w, b) -> torch.Tensor"}
r, c = R(rng, ROWS), R(rng, COLS)
vs = [{"desc": "two-pass mean/var", "code": f"""
import torch, triton, triton.language as tl
@triton.jit
def _k(x, w, b, o, C, BLK: tl.constexpr):
{r} = tl.program_id(0)
{c} = tl.arange(0, BLK)
m = {c} < C
v = tl.load(x + {r} * C + {c}, mask=m, other=0.).to(tl.float32)
mu = tl.sum(v, 0) / C
d = tl.where(m, v - mu, 0.0)
var = tl.sum(d * d, 0) / C
inv = 1.0 / tl.sqrt(var + 1e-5)
wt = tl.load(w + {c}, mask=m, other=0.).to(tl.float32)
bt = tl.load(b + {c}, mask=m, other=0.).to(tl.float32)
tl.store(o + {r} * C + {c},
((v - mu) * inv * wt + bt).to(o.dtype.element_ty), mask=m)
def run(x, w, b):
R, C = x.shape
o = torch.empty_like(x)
_k[(R,)](x, w, b, o, C, {NB})
return o
"""}, {"desc": "welford fused stats", "code": f"""
import torch, triton, triton.language as tl
@triton.jit
def _k(x, w, b, o, C, BLK: tl.constexpr):
{r} = tl.program_id(0)
{c} = tl.arange(0, BLK)
m = {c} < C
v = tl.load(x + {r} * C + {c}, mask=m, other=0.).to(tl.float32)
mu = tl.sum(v, 0) / C
var = tl.sum(v * v, 0) / C - mu * mu
inv = 1.0 / tl.sqrt(var + 1e-5)
wt = tl.load(w + {c}, mask=m, other=0.).to(tl.float32)
bt = tl.load(b + {c}, mask=m, other=0.).to(tl.float32)
tl.store(o + {r} * C + {c},
((v - mu) * inv * wt + bt).to(o.dtype.element_ty), mask=m)
def run(x, w, b):
R, C = x.shape
o = torch.empty_like(x)
_k[(R,)](x, w, b, o, C, {NB}, num_warps={rng.choice([4, 8])})
return o
"""}]
return spec, vs
def fam_add_rmsnorm(rng):
R_, C = rng.choice([512, 1024, 2048]), rng.choice([2048, 4096])
NB = 1 << (C - 1).bit_length()
spec = {"name": "add_rmsnorm",
"inputs": [("x", (R_, C)), ("r", (R_, C)), ("w", (C,))],
"ref": ("(x + r) * torch.rsqrt((x+r).pow(2)."
"mean(-1,keepdim=True)+1e-6) * w"),
"shapes": {"x": [R_, C], "r": [R_, C], "w": [C]},
"dtype": "bf16", "tol": 3e-2,
"sig": "def run(x, r, w) -> torch.Tensor"}
rr, cc = R(rng, ROWS), R(rng, COLS)
vs = [{"desc": "fused add+rmsnorm single pass", "code": f"""
import torch, triton, triton.language as tl
@triton.jit
def _k(x, r, w, o, C, BLK: tl.constexpr):
{rr} = tl.program_id(0)
{cc} = tl.arange(0, BLK)
m = {cc} < C
a = tl.load(x + {rr} * C + {cc}, mask=m, other=0.).to(tl.float32)
b_ = tl.load(r + {rr} * C + {cc}, mask=m, other=0.).to(tl.float32)
s = a + b_
inv = 1.0 / tl.sqrt(tl.sum(s * s, 0) / C + 1e-6)
wt = tl.load(w + {cc}, mask=m, other=0.).to(tl.float32)
tl.store(o + {rr} * C + {cc}, (s * inv * wt).to(o.dtype.element_ty),
mask=m)
def run(x, r, w):
R, C = x.shape
o = torch.empty_like(x)
_k[(R,)](x, r, w, o, C, {NB})
return o
"""}]
return spec, vs
def fam_rope(rng):
B, H, T, D = 2, rng.choice([4, 8]), rng.choice([1024, 2048]), 128
spec = {"name": "rope_pairwise",
"inputs": [("q", (B, H, T, D)), ("cos", (T, D // 2)),
("sin", (T, D // 2))],
"ref": ("torch.cat([q[..., :{hd}]*cos - q[..., {hd}:]*sin,"
" q[..., {hd}:]*cos + q[..., :{hd}]*sin], -1)"
.format(hd=D // 2)),
"shapes": {"q": [B, H, T, D], "cos": [T, D // 2],
"sin": [T, D // 2]},
"dtype": "bf16", "tol": 3e-2,
"sig": "def run(q, cos, sin) -> torch.Tensor"}
vs = [{"desc": "flat pairwise rope", "code": f"""
import torch, triton, triton.language as tl
@triton.jit
def _k(q, cs, sn, o, T, D: tl.constexpr):
bht = tl.program_id(0)
t = bht % T
d = tl.arange(0, D // 2)
c = tl.load(cs + t * (D // 2) + d)
s = tl.load(sn + t * (D // 2) + d)
base = q + bht * D
x1 = tl.load(base + d).to(tl.float32)
x2 = tl.load(base + D // 2 + d).to(tl.float32)
tl.store(o + bht * D + d, (x1 * c - x2 * s).to(o.dtype.element_ty))
tl.store(o + bht * D + D // 2 + d,
(x2 * c + x1 * s).to(o.dtype.element_ty))
def run(q, cos, sin):
B, H, T, D = q.shape
o = torch.empty_like(q)
_k[(B * H * T,)](q.reshape(B * H * T, D), cos, sin,
o.reshape(B * H * T, D), T, D)
return o
"""}]
return spec, vs
def fam_attention(rng):
T = rng.choice([256, 512])
H = rng.choice([4, 8])
D = 64
spec = {"name": "causal_attn_small",
"inputs": [("q", (1, H, T, D)), ("k", (1, H, T, D)),
("v", (1, H, T, D))],
"ref": ("torch.nn.functional.scaled_dot_product_attention"
"(q, k, v, is_causal=True)"),
"shapes": {"q": [1, H, T, D], "k": [1, H, T, D],
"v": [1, H, T, D]},
"dtype": "bf16", "tol": 3e-2,
"sig": "def run(q, k, v) -> torch.Tensor"}
vs = []
for bm, bn in [(64, 64), (128, 64)]:
vs.append({"desc": f"flash-style online softmax BM{bm} BN{bn}",
"code": f"""
import torch, triton, triton.language as tl
@triton.jit
def _k(q, k, v, o, T, D: tl.constexpr, BM: tl.constexpr,
BN: tl.constexpr):
h = tl.program_id(0)
pm = tl.program_id(1)
rm = pm * BM + tl.arange(0, BM)
mm = rm < T
qd = tl.arange(0, D)
Q = tl.load(q + h * T * D + rm[:, None] * D + qd[None, :],
mask=mm[:, None], other=0.).to(tl.float32)
acc = tl.zeros((BM, D), dtype=tl.float32)
m_i = tl.full((BM,), float('-inf'), tl.float32)
l_i = tl.zeros((BM,), tl.float32)
scale = 1.0 / tl.sqrt(float(D))
for n0 in range(0, T, BN):
rn = n0 + tl.arange(0, BN)
mn = rn < T
K = tl.load(k + h * T * D + rn[:, None] * D + qd[None, :],
mask=mn[:, None], other=0.).to(tl.float32)
V = tl.load(v + h * T * D + rn[:, None] * D + qd[None, :],
mask=mn[:, None], other=0.).to(tl.float32)
s = tl.dot(Q, tl.trans(K)) * scale
caus = (rm[:, None] >= rn[None, :])
s = tl.where(caus & mn[None, :], s, float('-inf'))
m_new = tl.maximum(m_i, tl.max(s, 1))
al = tl.exp(m_i - m_new)
p = tl.exp(s - m_new[:, None])
l_i = l_i * al + tl.sum(p, 1)
acc = acc * al[:, None] + tl.dot(p.to(V.dtype), V)
m_i = m_new
acc = acc / l_i[:, None]
tl.store(o + h * T * D + rm[:, None] * D + qd[None, :],
acc.to(o.dtype.element_ty), mask=mm[:, None])
def run(q, k, v):
B, H, T, D = q.shape
o = torch.empty_like(q)
_k[(B * H, triton.cdiv(T, {bm}))](q.reshape(B * H, T, D),
k.reshape(B * H, T, D),
v.reshape(B * H, T, D),
o.reshape(B * H, T, D),
T, D, {bm}, {bn},
num_warps={rng.choice([4, 8])})
return o
"""})
return spec, vs
def fam_topk(rng):
R_, C = rng.choice([512, 1024]), 4096
KK = rng.choice([8, 32])
spec = {"name": "topk_rows",
"inputs": [("x", (R_, C))],
"ref": "x.topk({k}, -1).values".format(k=KK),
"shapes": {"x": [R_, C]}, "dtype": "bf16", "tol": 2e-2,
"sig": "def run(x) -> torch.Tensor"}
vs = [{"desc": "iterative masked argmax", "code": f"""
import torch, triton, triton.language as tl
@triton.jit
def _k(x, o, C, K: tl.constexpr, BLK: tl.constexpr):
r = tl.program_id(0)
c = tl.arange(0, BLK)
m = c < C
v = tl.load(x + r * C + c, mask=m, other=float('-inf')).to(tl.float32)
for i in tl.static_range(K):
mx = tl.max(v, 0)
am = tl.argmax(v, 0)
v = tl.where(c == am, float('-inf'), v)
tl.store(o + r * K + i, mx.to(o.dtype.element_ty))
def run(x):
R, C = x.shape
o = torch.empty(R, {KK}, device=x.device, dtype=x.dtype)
_k[(R,)](x, o, C, {KK}, {1 << (C - 1).bit_length()})
return o
"""}]
return spec, vs
def fam_gather(rng):
V, D, N = 32768, rng.choice([512, 1024]), 8192
spec = {"name": "embedding_gather",
"inputs": [("emb", (V, D)), ("idx", (N,), V)],
"ref": "emb[idx.long()]",
"shapes": {"emb": [V, D], "idx": [N]}, "dtype": "bf16",
"tol": 0, "sig": "def run(emb, idx) -> torch.Tensor"}
vs = []
for bs in [256, 1024]:
vs.append({"desc": f"row-per-program gather BS{bs}", "code": f"""
import torch, triton, triton.language as tl
@triton.jit
def _k(emb, idx, o, D, BS: tl.constexpr):
i = tl.program_id(0) * BS + tl.arange(0, BS)
m = i < tl.num_programs(0) * BS
r = tl.load(idx + i, mask=i < {N})
d = tl.arange(0, 64)
for d0 in range(0, D, 64):
dd = d0 + d
v = tl.load(emb + r[:, None] * D + dd[None, :],
mask=(i < {N})[:, None], other=0.)
tl.store(o + i[:, None] * D + dd[None, :], v,
mask=(i < {N})[:, None])
def run(emb, idx):
N, D = idx.numel(), emb.size(1)
o = torch.empty(N, D, device=emb.device, dtype=emb.dtype)
_k[(triton.cdiv(N, {bs}),)](emb, idx, o, D, {bs})
return o
"""})
return spec, vs
def fam_transpose(rng):
N_ = rng.choice([2048, 4096, 8192])
spec = {"name": "transpose_2d",
"inputs": [("x", (N_, N_))],
"ref": "x.t().contiguous()",
"shapes": {"x": [N_, N_]}, "dtype": "bf16", "tol": 0,
"sig": "def run(x) -> torch.Tensor"}
vs = []
for bs in [32, 64]:
vs.append({"desc": f"tiled transpose {bs}x{bs}", "code": f"""
import torch, triton, triton.language as tl
@triton.jit
def _k(x, o, N, BS: tl.constexpr):
pi = tl.program_id(0); pj = tl.program_id(1)
ri = pi * BS + tl.arange(0, BS)
rj = pj * BS + tl.arange(0, BS)
mi = ri < N; mj = rj < N
v = tl.load(x + ri[:, None] * N + rj[None, :],
mask=mi[:, None] & mj[None, :], other=0.)
tl.store(o + rj[:, None] * N + ri[None, :], tl.trans(v),
mask=mj[:, None] & mi[None, :])
def run(x):
N = x.size(0)
o = torch.empty_like(x)
_k[(triton.cdiv(N, {bs}), triton.cdiv(N, {bs}))](x, o, N, {bs})
return o
"""})
return spec, vs
def fam_adamw(rng):
N_ = rng.choice([1 << 20, 1 << 22])
spec = {"name": "adamw_fused",
"inputs": [("p", (N_,)), ("g", (N_,)), ("m", (N_,)),
("v", (N_,), "pos")],
"ref": ("p.float() - 3e-4 * ((m.float() * 0.9 + g.float() * 0.1)"
" / (1 - 0.9)) / ((v.float() * 0.95 + g.float() * "
"g.float() * 0.05) / (1 - 0.95)).sqrt()"
" - 3e-4 * 0.1 * p.float()"),
"shapes": {n: [N_] for n in "pgmv"},
"dtype": "bf16", "tol": 4e-2,
"sig": "def run(p, g, m, v) -> torch.Tensor"}
vs = [{"desc": "fused adamw update fp32 math", "code": f"""
import torch, triton, triton.language as tl
@triton.jit
def _k(p, g, m, v, o, N, BS: tl.constexpr):
i = tl.program_id(0) * BS + tl.arange(0, BS)
mm = i < N
pp = tl.load(p + i, mask=mm, other=0.).to(tl.float32)
gg = tl.load(g + i, mask=mm, other=0.).to(tl.float32)
mm1 = tl.load(m + i, mask=mm, other=0.).to(tl.float32)
vv = tl.load(v + i, mask=mm, other=0.).to(tl.float32)
m_new = mm1 * 0.9 + gg * 0.1
v_new = vv * 0.95 + gg * gg * 0.05
upd = (m_new / (1 - 0.9)) / tl.sqrt(v_new / (1 - 0.95))
y = pp - 3e-4 * upd - 3e-4 * 0.1 * pp
tl.store(o + i, y.to(o.dtype.element_ty), mask=mm)
def run(p, g, m, v):
o = torch.empty_like(p)
_k[(triton.cdiv(p.numel(), 1024),)](p, g, m, v, o, p.numel(), 1024)
return o
"""}]
return spec, vs
def fam_matvec(rng):
M, K = 4096, rng.choice([4096, 8192])
spec = {"name": "matvec",
"inputs": [("a", (M, K)), ("b", (K,))],
"ref": "a @ b",
"shapes": {"a": [M, K], "b": [K]}, "dtype": "bf16",
"tol": 3e-2, "sig": "def run(a, b) -> torch.Tensor"}
vs = [{"desc": "row-dot per program", "code": f"""
import torch, triton, triton.language as tl
@triton.jit
def _k(a, b, o, K, BK: tl.constexpr):
r = tl.program_id(0)
acc = 0.0
for k0 in range(0, K, BK):
kk = k0 + tl.arange(0, BK)
m = kk < K
av = tl.load(a + r * K + kk, mask=m, other=0.).to(tl.float32)
bv = tl.load(b + kk, mask=m, other=0.).to(tl.float32)
acc += tl.sum(av * bv, 0)
tl.store(o + r, acc.to(o.dtype.element_ty))
def run(a, b):
M, K = a.shape
o = torch.empty(M, device=a.device, dtype=a.dtype)
_k[(M,)](a, b, o, K, 2048, num_warps={rng.choice([4, 8])})
return o
"""}]
return spec, vs
FAMILIES = [fam_elementwise, fam_softmax, fam_rmsnorm, fam_gemm,
fam_reduction, fam_conv1d, fam_cumsum, fam_layernorm,
fam_add_rmsnorm, fam_rope, fam_attention, fam_topk,
fam_gather, fam_transpose, fam_adamw, fam_matvec]
# ---------------------------------------------------------------------------
# grading: exec code in THIS process (invoked via --grade subprocess)
# ---------------------------------------------------------------------------
def grade_local(spec_json, code):
spec = json.loads(spec_json)
import linecache
import time
import types
import torch
dev = "cuda"
torch.manual_seed(0)
dt = torch.bfloat16 if spec["dtype"] == "bf16" else torch.float16
ins = []
for spec_in in spec["inputs"]:
_, sh = spec_in[0], spec_in[1]
if len(spec_in) > 2 and spec_in[2] == "pos":
ins.append(torch.rand(sh, device=dev).to(dt))
elif len(spec_in) > 2: # int tensor: randint(hi)
ins.append(torch.randint(0, spec_in[2], sh, device=dev))
else:
ins.append(torch.randn(sh, device=dev).to(dt))
names = [n for n, *_ in spec["inputs"]]
ref = eval(f"lambda {','.join(names)}: {spec['ref']}",
{"torch": torch})
want = ref(*ins).float()
mod = types.ModuleType("gen")
linecache.cache["<gen>"] = (len(code), None,
code.splitlines(True), "<gen>")
import triton # noqa
import triton.language as tl # noqa
glb = {"torch": torch, "triton": triton, "tl": tl}
try:
exec(compile(code, "<gen>", "exec"), glb)
fn = glb["run"]
got = fn(*ins).float()
err = (got - want).abs().max().item()
rel = err / max(want.abs().max().item(), 1e-9)
if rel > spec["tol"] or not torch.isfinite(got).all():
print(json.dumps({"ok": False, "stage": "wrong",
"rel": rel}))
return
for _ in range(3):
fn(*ins)
torch.cuda.synchronize()
t0 = time.perf_counter()
for _ in range(10):
fn(*ins)
torch.cuda.synchronize()
t_gen = (time.perf_counter() - t0) / 10
for _ in range(3):
ref(*ins)
torch.cuda.synchronize()
t0 = time.perf_counter()
for _ in range(10):
ref(*ins)
torch.cuda.synchronize()
t_ref = (time.perf_counter() - t0) / 10
print(json.dumps({"ok": True, "rel": rel, "ms": t_gen * 1e3,
"ref_ms": t_ref * 1e3,
"speedup": t_ref / max(t_gen, 1e-9)}))
except Exception as e:
print(json.dumps({"ok": False, "stage": "exec",
"err": str(e)[:300]}))
finally:
linecache.cache.pop("<gen>", None)
def grade(spec, code, timeout=120):
with tempfile.NamedTemporaryFile("w", suffix=".json",
delete=False) as f:
json.dump(spec, f)
tf = f.name
try:
r = subprocess.run([sys.executable, os.path.abspath(__file__),
"--grade", tf], input=code,
capture_output=True, text=True,
timeout=timeout)
lines = r.stdout.strip().splitlines()
if not lines:
return {"ok": False, "stage": "crash",
"err": r.stderr[-200:]}
return json.loads(lines[-1])
except subprocess.TimeoutExpired:
return {"ok": False, "stage": "timeout"}
finally:
os.unlink(tf)
# ---------------------------------------------------------------------------
# episode rendering
# ---------------------------------------------------------------------------
def render_episode(spec, graded, rng):
"""Corpus-native episode: TASK/KERNEL/OBJECTIVE header, then
attempt -> RESULT/BEST/HISTORY blocks exactly like kernelstrain.
graded: list of (variant_desc, code, verdict) in attempt order."""
shape = {s_in[0]: list(s_in[1]) for s_in in spec["inputs"]}
sig = spec["sig"].replace("def run", "run").replace(" -> ", " -> ")
parts = [
M_PROMPT,
"You are a kernel optimization agent. Given an optimization "
"task and the trajectory so far, write the next complete "
"kernel candidate. Output code only.",
f"TASK triton {spec['name']} | gpu=mi350x arch=gfx950 | "
f"dtype={spec['dtype']} | shape={shape}",
f"KERNEL {sig[4:] if sig.startswith('def ') else sig}",
"OBJECTIVE minimize latency_ms",
"Write the baseline kernel.",
M_KERNEL]
best_ms, history = None, []
for i, (desc, code, v) in enumerate(graded):
parts.append(code.strip())
parts.append(M_EOS)
tag = desc.replace(" ", "_")[:24]
if v["ok"]:
ms, sp = v["ms"], v.get("speedup")
best_ms = ms if best_ms is None else min(best_ms, ms)
verdict = "KEPT" if ms <= best_ms else "DISCARD"
obs = [f"RESULT step {i}: ok time_ms={ms:.4f} "
f"tflops={v.get('speedup', 0):.2f} {verdict}"]
else:
obs = [f"RESULT step {i}: {v['stage']} "
f"err={str(v.get('err', ''))[:80]} FAIL"]
history.append(f"step {i} {tag} "
f"{'ok' if v['ok'] else v['stage']} "
f"{v.get('ms', 0):.3f}ms "
f"{'KEPT' if v['ok'] else 'FAIL'}")
obs.append(f"BEST step {i}: time_ms="
f"{best_ms if best_ms else 0:.4f}")
obs.append("HISTORY")
obs.extend(history)
obs.append("Write the next candidate kernel. "
"Output code only.")
parts.append(M_OBS + "\n" + "\n".join(obs))
if i < len(graded) - 1:
parts.append(M_KERNEL)
parts.append(M_DONE + "\n")
return "\n".join(parts)
def build_episode(fam_fn, rng, workers=1):
spec, variants = fam_fn(rng)
rng.shuffle(variants)
if workers > 1:
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(workers) as ex:
verdicts = list(ex.map(
lambda v: grade(spec, v["code"]), variants))
else:
verdicts = [grade(spec, v["code"]) for v in variants]
graded = [(v["desc"], v["code"], verdict)
for v, verdict in zip(variants, verdicts)]
return spec, graded
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--grade", nargs=1, metavar="SPEC_JSON",
help=argparse.SUPPRESS)
ap.add_argument("--out", default="synth_eps.jsonl")
ap.add_argument("--episodes", type=int, default=200)
ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--workers", type=int, default=1)
args = ap.parse_args()
if args.grade:
spec_json = open(args.grade[0]).read()
grade_local(spec_json, sys.stdin.read())
return
rng = random.Random(args.seed)
n_ok = n_eps = attempts = 0
max_attempts = args.episodes * 4
with open(args.out, "w") as f:
while n_eps < args.episodes and attempts < max_attempts:
attempts += 1
fam_fn = FAMILIES[attempts % len(FAMILIES)]
spec, graded = build_episode(fam_fn, rng, args.workers)
oks = sum(1 for _, _, v in graded if v["ok"])
n_ok += oks
if oks == 0:
stages = [v.get("stage", "?") for _, _, v in graded]
errs = [v.get("err", "")[:100] for _, _, v in graded
if v.get("err")]
print(f"[skip] {spec['name']}: stages={stages} "
f"{errs[:1]}", flush=True)
continue # no signal, skip
ep = render_episode(spec, graded, rng)
f.write(json.dumps({"text": ep, "spec": spec["name"],
"ok_variants": oks,
"n_variants": len(graded)}) + "\n")
f.flush()
n_eps += 1
print(f"[{n_eps}/{args.episodes}] {spec['name']:18s} "
f"{oks}/{len(graded)} correct", flush=True)
print(f"done: {n_eps} episodes, {n_ok} verified variants -> {args.out}")
if __name__ == "__main__":
main()