File size: 6,344 Bytes
0f775e2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 | """Llama-shaped decoder with INT4 group-quantised weights (W4A16), shipped pre-packed.
Every 2-D weight arrives as a triple `(packed, scale, zero)`:
packed : (out, in // 2) uint8 -- two 4-bit codes per byte, LOW nibble first
scale : (out, in // group) bf16
zero : (out, in // group) uint8 (values 0..15)
and its value is `(code - zero) * scale`, with `group` = `cfg["group"]` contiguous input elements
sharing one (scale, zero). This is the AWQ / GPTQ asymmetric layout.
The weights are quantised ONCE, here, and the reference dequantises exactly these bytes. That is not a
convenience: if the fixture were fp32 and the agent had to quantise, a *correct* int4 kernel would
disagree with the reference by the quantisation error rather than by its own error -- measured at 10x
the tolerance for the fp8 case.
"""
from model import HELPERS_CORE
QUANT = r'''
_INT4_GROUP = None # set by make_weights / build_model from cfg
def _quantise(w, dt, group=128):
"""fp32 -> asymmetric int4 with per-group (scale, zero), packed two codes per byte."""
if dt == "bf16":
return w.to(torch.bfloat16)
if dt != "int4":
raise ValueError(dt)
out, inn = w.shape
g = w.view(out, inn // group, group)
lo = g.amin(dim=-1, keepdim=True)
hi = g.amax(dim=-1, keepdim=True)
scale = ((hi - lo) / 15.0).clamp(min=1e-8)
zero = torch.round(-lo / scale).clamp(0, 15)
code = torch.round(g / scale + zero).clamp(0, 15).to(torch.uint8).view(out, inn)
packed = (code[:, 0::2] | (code[:, 1::2] << 4)).contiguous()
return (packed, scale.squeeze(-1).to(torch.bfloat16), zero.squeeze(-1).to(torch.uint8))
def _deq(w, group=128):
"""(packed, scale, zero) -> bf16. Plain bf16 weights pass through."""
if not isinstance(w, tuple):
return w
packed, scale, zero = w
out = packed.shape[0]
lo = (packed & 0xF).to(torch.int16)
hi = (packed >> 4).to(torch.int16)
code = torch.stack([lo, hi], dim=-1).view(out, -1) # interleave back to (out, in)
inn = code.shape[1]
code = code.view(out, inn // group, group).float()
v = (code - zero.float().unsqueeze(-1)) * scale.float().unsqueeze(-1)
return v.view(out, inn).to(torch.bfloat16)
'''
BODY = r'''
def make_weights(cfg, seed=0, device="cuda"):
"""Deterministic 1/sqrt(fan_in)-scaled weights, shipped ALREADY int4-quantised."""
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"]
dt, grp = cfg["wdtype"], cfg["group"]
def rnd(*shape, fan_in):
w = torch.randn(*shape, device=device, dtype=torch.float32, generator=g) / (fan_in ** 0.5)
return _quantise(w, dt, grp)
ones = lambda: torch.ones(d, device=device, dtype=torch.bfloat16)
W = {"embed": rnd(cfg["vocab"], d, fan_in=d), "final_norm": ones(), "layers": []}
for _ in range(cfg["layers"]):
W["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 W
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 build_model(weights, kv_cache, cfg, max_seq_len):
"""UNTIMED setup. Dequantises ONCE here rather than per step -- dequantising inside every step
allocates GBs per call, which perturbs the caching allocator enough that cuBLAS picks different
GEMV algorithms run-to-run and two bit-identical implementations drift apart."""
cos, sin = _rope_cache(cfg, max_seq_len, weights["final_norm"].device)
grp = cfg["group"]
W = {"embed": _deq(weights["embed"], grp), "final_norm": weights["final_norm"],
"layers": [{k: (v if k.endswith("norm") else _deq(v, grp)) for k, v in L.items()}
for L in weights["layers"]]}
return {"W": W, "kv": kv_cache, "cfg": cfg, "cos": cos, "sin": sin}
@torch.no_grad()
def decode_step(handle, token_ids, pos):
"""One decode step for every sequence in the batch. Appends this position's K/V into the cache.
token_ids: (B,) int64 pos: int, the absolute position being written
returns: (B, vocab) logits
"""
W, kv, cfg = handle["W"], handle["kv"], handle["cfg"]
cos, sin = handle["cos"], handle["sin"]
B = token_ids.shape[0]
n_q, n_kv, hd = cfg["n_q"], cfg["n_kv"], cfg["hd"]
rep = n_q // n_kv
x = W["embed"][token_ids]
for li, L in enumerate(W["layers"]):
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)
x = _rms_norm(x, W["final_norm"], cfg["eps"])
return x @ W["embed"].T # tied lm_head
'''
MODEL_SRC = HELPERS_CORE + QUANT + BODY
|