File size: 7,114 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
141
142
143
144
145
146
147
148
149
150
151
152
153
"""Llama-shaped decoder with NVFP4 weights, shipped pre-quantised.

NVFP4 is the Blackwell 4-bit format: values are **e2m1** (1 sign, 2 exponent, 1 mantissa bit), grouped
in blocks of 16 along the input dimension, each block carrying an **e4m3** scale, and the whole tensor
carrying one fp32 global scale. Every 2-D weight arrives as a triple:

    packed : (out, in // 2) uint8            -- two e2m1 codes per byte, LOW nibble first
    bscale : (out, in // 16) float8_e4m3fn   -- per-block scale
    gscale : () float32                      -- per-tensor scale

and its value is `E2M1[code] * bscale.float() * gscale`.

The e2m1 magnitude ladder is exactly `[0, .5, 1, 1.5, 2, 3, 4, 6]`; the nibble is `sign << 3 | mag`.
That ladder is the whole reason the format is interesting: it is not uniform, so a dequantisation is a
7-entry table lookup rather than a multiply-add, and the natural implementation is a small LUT held in
registers or shared memory while the packed bytes stream past.

The weights are quantised ONCE, here, and the reference dequantises exactly these bytes -- the agent is
graded on its kernel, not on its rounding policy.
"""
from model import HELPERS_CORE

QUANT = r'''
# e2m1: 3 magnitude bits -> this ladder; bit 3 is the sign.
_E2M1 = [0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0]


def _e2m1_lut(device):
    """16-entry signed lookup: index = nibble, value = the represented number."""
    v = torch.tensor(_E2M1, device=device, dtype=torch.float32)
    return torch.cat([v, -v])


def _quantise(w, dt, block=16):
    """fp32 -> NVFP4 (packed e2m1 nibbles, per-block e4m3 scale, per-tensor fp32 scale)."""
    if dt == "bf16":
        return w.to(torch.bfloat16)
    if dt != "nvfp4":
        raise ValueError(dt)
    out, inn = w.shape
    g = w.view(out, inn // block, block)
    bamax = g.abs().amax(dim=-1, keepdim=True)                       # (out, nb, 1)
    gscale = (w.abs().amax() / (6.0 * 448.0)).clamp(min=1e-12)
    bs = (bamax / 6.0 / gscale).clamp(min=1e-6, max=448.0).to(torch.float8_e4m3fn)
    eff = bs.float() * gscale                                        # the scale actually stored
    n = (g / eff.clamp(min=1e-12)).clamp(-6.0, 6.0)
    ladder = torch.tensor(_E2M1, device=w.device, dtype=torch.float32)
    mag = torch.argmin((n.abs().unsqueeze(-1) - ladder).abs(), dim=-1).to(torch.uint8)
    code = (mag | ((n < 0).to(torch.uint8) << 3)).view(out, inn)
    packed = (code[:, 0::2] | (code[:, 1::2] << 4)).contiguous()
    return (packed, bs.squeeze(-1), gscale)


def _deq(w, block=16):
    """(packed, bscale, gscale) -> bf16. Plain bf16 weights pass through."""
    if not isinstance(w, tuple):
        return w
    packed, bs, gs = w
    out = packed.shape[0]
    lo = (packed & 0xF).to(torch.int64)
    hi = (packed >> 4).to(torch.int64)
    code = torch.stack([lo, hi], dim=-1).view(out, -1)
    inn = code.shape[1]
    v = _e2m1_lut(packed.device)[code].view(out, inn // block, block)
    v = v * (bs.float() * gs).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 NVFP4-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, blk = cfg["wdtype"], cfg["block"]

    def rnd(*shape, fan_in):
        w = torch.randn(*shape, device=device, dtype=torch.float32, generator=g) / (fan_in ** 0.5)
        return _quantise(w, dt, blk)

    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)
    blk = cfg["block"]
    W = {"embed": _deq(weights["embed"], blk), "final_norm": weights["final_norm"],
         "layers": [{k: (v if k.endswith("norm") else _deq(v, blk)) 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