KBench / tools /mega_factory /models /head_sample.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
7.5 kB
"""Final RMSNorm -> tied LM head -> temperature -> min-p filter -> inverse-CDF sample, in one kernel.
A serving stack samples for every running sequence at every step. Done as separate ops that is a
128k-wide logit matrix written to HBM, read back for a max, read back for a sum, read back for a
filter, read back for a prefix sum, and read back once more to pick a token: 1024 x 128256 fp32 is
525 MB per pass, several times over, next to a 525 MB weight read. Fused, the logits never exist.
Sampling is stochastic, so this task does NOT grade token equality. `compare` scores two things:
* a deterministic per-row summary (max logit, full log-sum-exp, log of the kept mass), by relative
error -- this pins the norm, the projection, the temperature and the filter threshold exactly; and
* the sampled tokens *statistically*, against the reference's own distribution: every token must lie
in the kept support, and the mean surprisal of the drawn tokens must match the entropy of the
filtered distribution. Correct samplers pass at any seed; argmax, unfiltered sampling and
uniform-over-support all miss by a wide margin.
The surprisal term is scored under `e / kept_sum` rather than under `q`, which matters only for a
token sitting in the support check's slack band -- see the long comment in `compare`. Scoring it under
`q` charged such a token 69 nats and failed CORRECT implementations at z = 15-30.
The reference stashes its filtered distribution in a module global so `compare` can score the
submission's tokens under the *reference's* probabilities -- a submission cannot fabricate them.
"""
from model import HELPERS_CORE
BODY = r'''
_REF = {}
_TOL = 1e-2 # the task's tolerance; compare() scales every check into these units
_ZCRIT = 8.0 # the statistical check spends the whole tolerance at 8 sigma
def make_weights(cfg, seed=0, device="cuda"):
"""Tied LM head: the embedding matrix, plus the final RMSNorm gain."""
g = torch.Generator(device=device).manual_seed(seed)
d = cfg["d"]
e = (torch.randn(cfg["vocab"], d, device=device, dtype=torch.float32, generator=g)
/ (d ** 0.5)).to(torch.bfloat16)
return {"embed": e, "final_norm": torch.ones(d, device=device, dtype=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):
"""(x, u) per call -- B hidden states and B uniform variates in [0, 1)."""
g = torch.Generator(device="cuda").manual_seed(seed)
out = []
for _ in range(n):
x = torch.randn(batch, cfg["d"], device="cuda", dtype=torch.float32,
generator=g).to(torch.bfloat16)
u = torch.rand(batch, device="cuda", dtype=torch.float32, generator=g)
out.append((x, u))
return out
def build_head(weights, kv_cache, cfg, max_seq_len):
"""UNTIMED setup. Re-tile the embedding, allocate scratch, launch a persistent kernel, ..."""
return {"W": weights, "cfg": cfg}
@torch.no_grad()
def sample_step(handle, x, u):
"""Norm, project to the vocabulary, min-p filter, and draw one token per row.
x : (B, d) bf16 the final hidden state of each running sequence
u : (B,) fp32 one uniform variate per row, in [0, 1)
returns : (tokens, aux) -- tokens (B,) int64; aux (B, 3) fp32 = [max_logit, lse, log_kept_mass]
"""
W, cfg = handle["W"], handle["cfg"]
minp = cfg["min_p"]
h = _rms_norm(x, W["final_norm"], cfg["eps"])
z = torch.matmul(h, W["embed"].T).float() * (1.0 / cfg["temperature"]) # (B, vocab)
m = z.amax(-1, keepdim=True)
e = torch.exp(z - m) # e_max == 1, so p_i >= min_p * p_max <=> e_i >= min_p
se = e.sum(-1, keepdim=True)
kept = e * (e >= minp)
ks = kept.sum(-1, keepdim=True)
q = kept / ks # renormalised filtered distribution
cdf = q.cumsum(-1)
tok = torch.searchsorted(cdf.contiguous(), u.unsqueeze(1).contiguous())
tok = tok.clamp_(max=cfg["vocab"] - 1).squeeze(1)
_REF.update(e=e, q=q, ks=ks, minp=minp) # ground truth for the statistical check
return tok, torch.cat([m, m + se.log(), (ks / se).log()], dim=1)
def compare(got, exp):
"""Deterministic summary by relative error; sampled tokens by a statistical test.
Returns one scalar in tolerance units -- the max of
* relative error of `aux` (already in those units),
* 10x the fraction of drawn tokens outside the reference's kept support, with a 2x slack band
on the threshold so a boundary token is never punished, and
* the surprisal z-score, scaled so that |z| = 8 exactly spends the tolerance.
The z-score is the honest way to do this. For a correct draw from `q`, the surprisal
`-log q(token)` has mean `H(q)` and variance `V(q)` (the varentropy) for each row, so the mean
over B independent rows is `mean(H)` with standard error `sqrt(sum(V))/B` -- a quantity computed
from the reference's own distribution, with nothing to tune. A correct sampler gives |z| ~ N(0,1)
at any seed; at B = 1024 an argmax gives z = 33.8, uniform-over-support 33.6 and unfiltered
sampling 3064 (measured). The limit is eight sigma; the worst |z| over 24 correct draws was 3.19.
The probabilities used are the REFERENCE's, recorded by the reference call that ran immediately
before this comparison, so a submission cannot influence its own statistical score.
"""
gt, ga = got
et, ea = exp
a = ((ga.float() - ea.float()).norm() / ea.float().norm().clamp(min=1e-9)).item()
e, q, ks, minp = _REF["e"], _REF["q"], _REF["ks"], _REF["minp"]
t = gt.reshape(-1).to(torch.int64)
B = q.shape[0]
if t.numel() != B or int(t.min()) < 0 or int(t.max()) >= q.shape[1]:
return 1.0
r = torch.arange(B, device=q.device)
out_of_support = (e[r, t] < 0.5 * minp).float().mean().item()
lq = q.clamp(min=1e-30).log()
Hrow = -(q * lq).sum(-1) # entropy per row
Vrow = ((q * lq * lq).sum(-1) - Hrow * Hrow).clamp(min=0) # varentropy per row
stderr = (Vrow.sum().sqrt() / B).clamp(min=1e-9)
# Surprisal is scored under e/ks, NOT under q. On every token the reference kept, the two are the
# same number, so the statistic is unchanged for a correct sampler. They differ only for a token
# in the 2x slack band -- one the support check above deliberately forgives -- where q is exactly
# 0 and -log q is 69 nats. Scoring those under q was a real defect: an independent but CORRECT
# implementation lands a handful of the 1024 rows in that band (its logits differ from the
# reference's by ~1.7e-3, so a token whose e sits within a per cent of the threshold falls the
# other way), and 7 rows x 69 nats moved the mean surprisal by 0.44 against a standard error of
# 0.029 -- z = 15 to 30 on a limit of 8. Measured: the same correct implementation scores 0.005
# under this line and 0.11 under the old one, against a tolerance of 0.03. A boundary token now
# scores just above the least likely KEPT token, and a token from far outside the support still
# scores enormously (and is caught by out_of_support besides).
ps = (e / ks).clamp(min=1e-30)
z = ((-ps[r, t].log()).mean() - Hrow.mean()).abs() / stderr
return max(a, 10.0 * out_of_support, _TOL * z.item() / _ZCRIT)
'''
MODEL_SRC = HELPERS_CORE + BODY