okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-own-2b (cc8c29f31) into f-own-int: our own GGUF reader/writer and quantizers (gguf-py out of the pack tools)0f1e5e4cb

main
9.2 KiB203 linesraw
1"""A plain-torch port of the DFlash2 drafter (z-lab/dflash model.py, DFlash2DraftModel) for the offline acceptance experiment.
2
3Everything is fp32 on the CPU. The target's embedding table and LM head are the dequantized tensors of OUR GGUF (IQ4_XS embedding,
4Q6_K head), the context features are the hidden states dumped by the engine's STRATA_TAP_FILE hook.
5"""
6import json, struct, sys
7import numpy as np
8import torch
9import torch.nn.functional as F
10from safetensors import safe_open
11
12import os
13sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
14from _paths import gguf_lib
15gguf = gguf_lib()
16dequantize = gguf.quants.dequantize
17
18
19def rms(x, w, eps=1e-6):
20    v = x.pow(2).mean(-1, keepdim=True)
21    return (x * torch.rsqrt(v + eps)) * w
22
23
24def rotate_half(x):
25    h = x.shape[-1] // 2
26    return torch.cat((-x[..., h:], x[..., :h]), dim=-1)
27
28
29def load_dequant(path, rows, cols, qtype):
30    raw = np.fromfile(path, dtype=np.uint8)
31    bs, ts = gguf.GGML_QUANT_SIZES[qtype]
32    raw = raw.reshape(rows, cols // bs * ts)
33    return torch.from_numpy(dequantize(raw, qtype).astype(np.float32).reshape(rows, cols))
34
35
36class Drafter:
37    def __init__(self, st_path, cfg_path, embed, head, threads=6):
38        torch.set_num_threads(threads)
39        cfg = json.load(open(cfg_path))
40        dc = cfg["dflash_config"]
41        self.H = cfg["hidden_size"]
42        self.L = cfg["num_hidden_layers"]
43        self.NH = cfg["num_attention_heads"]
44        self.NKV = cfg["num_key_value_heads"]
45        self.HD = cfg["head_dim"]
46        self.win = cfg["sliding_window"]
47        self.theta = cfg["rope_parameters"]["rope_theta"]
48        self.eps = cfg["rms_norm_eps"]
49        self.gs = dc["conv_group_size"]
50        self.ks = dc["conv_kernel_size"]
51        self.mask_id = dc["mask_token_id"]
52        self.top_k = dc["selector_top_k"]
53        self.taps = dc["target_layer_ids"]
54        self.embed = embed
55        self.head = head
56        self.w = {}
57        with safe_open(st_path, "pt") as f:
58            for k in f.keys():
59                t = f.get_tensor(k)
60                # the two codebooks stay bf16 (only gathered rows are used); everything else fp32
61                self.w[k] = t if "codebook" in k else t.float()
62        self.inv_freq = 1.0 / (self.theta ** (torch.arange(0, self.HD, 2, dtype=torch.float32) / self.HD))
63        self.Kc = None
64        self.fast_head = False
65        self.head_bf16 = None
66
67    def enable_fast_head(self):
68        self.head_bf16 = self.head.to(torch.bfloat16)
69        self.fast_head = True
70
71    def cos_sin(self, pos):
72        fr = pos.float()[:, None] * self.inv_freq[None, :]
73        emb = torch.cat([fr, fr], dim=-1)
74        return emb.cos(), emb.sin()
75
76    # ---- context: fc + hidden_norm over the tapped features, then every layer's K (norm + rope) and V
77    def set_context(self, feats):
78        """feats: [n, taps*H] float32, row j = the features of position j."""
79        w = self.w
80        h = rms(feats @ w["fc.weight"].T, w["hidden_norm.weight"], self.eps)
81        n = h.shape[0]
82        cos, sin = self.cos_sin(torch.arange(n))
83        self.Kc, self.Vc = [], []
84        for l in range(self.L):
85            p = "layers.%d.self_attn." % l
86            k = (h @ w[p + "k_proj.weight"].T).view(n, self.NKV, self.HD)
87            v = (h @ w[p + "v_proj.weight"].T).view(n, self.NKV, self.HD)
88            k = rms(k, w[p + "k_norm.weight"], self.eps)
89            k = k * cos[:, None, :] + rotate_half(k) * sin[:, None, :]
90            self.Kc.append(k.permute(1, 0, 2).contiguous())   # [NKV, n, HD]
91            self.Vc.append(v.permute(1, 0, 2).contiguous())
92
93    def conv(self, x, dyn, base):
94        """_grouped_dynamic_convolve over a block x [b, H]; dyn [b, ks, groups]; base [ks, H]."""
95        b, H = x.shape
96        groups = H // self.gs
97        blocks = x.view(b, groups, self.gs)
98        out = torch.zeros_like(blocks)
99        for o in range(base.shape[0]):
100            vals = blocks if o == 0 else F.pad(blocks[:-o], (0, 0, 0, 0, o, 0))
101            kern = base[o].float().view(1, groups, self.gs)
102            out = out + kern * vals
103            out = out + dyn[:, o, :, None] * vals
104        return out.view(b, H)
105
106    def prepare(self, x, p):
107        w = self.w
108        groups = self.H // self.gs
109        dyn = (x @ w[p + "kernel_projection.weight"].T).view(x.shape[0], 2, self.ks, groups)
110        return self.conv(x, dyn[:, 0], w[p + "base_kernel"][0]), dyn[:, 1]
111
112    def finish(self, x, dyn, p):
113        return self.conv(x, dyn, self.w[p + "base_kernel"][1])
114
115    # ---- one block: anchor token at position s (s >= 1), block size b; returns the drafted path (b-1 tokens), the candidate lists
116    def draft(self, s, anchor, b, greedy=True):
117        w = self.w
118        H, NH, NKV, HD = self.H, self.NH, self.NKV, self.HD
119        ids = torch.tensor([anchor] + [self.mask_id] * (b - 1))
120        h = self.embed[ids]                                  # [b, H]
121        pos = torch.arange(s, s + b)
122        cos, sin = self.cos_sin(pos)
123        # keys: context positions max(0, s-win+1) .. s-1 (a block row i sees ctx j when s+i-j < win), then the block
124        lo = max(0, s - self.win + 1)
125        for l in range(self.L):
126            p = "layers.%d." % l
127            r = h
128            x = rms(h, w[p + "input_layernorm.weight"], self.eps)
129            x, kdyn = self.prepare(x, p + "attention_conv.")
130            q = (x @ w[p + "self_attn.q_proj.weight"].T).view(b, NH, HD)
131            q = rms(q, w[p + "self_attn.q_norm.weight"], self.eps)
132            kn = rms((x @ w[p + "self_attn.k_proj.weight"].T).view(b, NKV, HD), w[p + "self_attn.k_norm.weight"], self.eps)
133            vn = (x @ w[p + "self_attn.v_proj.weight"].T).view(b, NKV, HD)
134            q = q * cos[:, None, :] + rotate_half(q) * sin[:, None, :]
135            kn = kn * cos[:, None, :] + rotate_half(kn) * sin[:, None, :]
136            Kc = self.Kc[l][:, lo:s, :]                      # [NKV, c, HD]
137            Vc = self.Vc[l][:, lo:s, :]
138            K = torch.cat([Kc, kn.permute(1, 0, 2)], dim=1)  # [NKV, c+b, HD]
139            V = torch.cat([Vc, vn.permute(1, 0, 2)], dim=1)
140            c = Kc.shape[1]
141            kpos = torch.cat([torch.arange(lo, s), pos])
142            vis = (pos[:, None] - kpos[None, :]).abs() < self.win          # [b, c+b]
143            rep = NH // NKV
144            Kx = K.repeat_interleave(rep, dim=0)             # [NH, c+b, HD]
145            Vx = V.repeat_interleave(rep, dim=0)
146            sc = torch.einsum("bhd,hkd->hbk", q, Kx) * (HD ** -0.5)
147            sc = sc.masked_fill(~vis[None], float("-inf"))
148            att = torch.softmax(sc, dim=-1)
149            o = torch.einsum("hbk,hkd->bhd", att, Vx).reshape(b, NH * HD)
150            o = o @ w[p + "self_attn.o_proj.weight"].T
151            o = self.finish(o, kdyn, p + "attention_conv.")
152            h = r + o
153            r = h
154            x = rms(h, w[p + "post_attention_layernorm.weight"], self.eps)
155            x, mdyn = self.prepare(x, p + "mlp_conv.")
156            m = (F.silu(x @ w[p + "mlp.gate_proj.weight"].T) * (x @ w[p + "mlp.up_proj.weight"].T)) @ w[p + "mlp.down_proj.weight"].T
157            m = self.finish(m, mdyn, p + "mlp_conv.")
158            h = r + m
159        self.last_all = rms(h, w["norm.weight"], self.eps)
160        out = self.last_all[1:]                              # rows 1..b-1
161        if self.fast_head:
162            # candidates from a bf16 pass over the table (7x faster on this CPU), then the exact fp32 logits of the 32 best decide the top 16
163            lb = (out.to(torch.bfloat16) @ self.head_bf16.T)
164            c32 = torch.topk(lb, 32, dim=-1, sorted=False).indices            # [b-1, 32]
165            ex = torch.einsum("rkh,rh->rk", self.head[c32], out)               # [b-1, 32] exact
166            unary, j16 = torch.topk(ex, self.top_k, dim=-1, sorted=False)
167            cand = c32.gather(-1, j16)
168            logits = None
169        else:
170            logits = out @ self.head.T                       # [b-1, V]
171            unary, cand = torch.topk(logits, self.top_k, dim=-1, sorted=False)
172        hp = out @ w["candidate_selector.hidden_projection.weight"].T   # [b-1, rank]
173        A = w["candidate_selector.predecessor_codebook"]
174        B = w["candidate_selector.successor_codebook"]
175        pred = anchor
176        path, probs = [], []
177        for i in range(b - 1):
178            sc = unary[i] + (B[cand[i]].float() @ (A[pred].float() * hp[i]))
179            j = int(torch.argmax(sc))
180            probs.append(float(torch.softmax(sc, dim=-1)[j]))   # the selector's own probability of the pick (a confidence)
181            pred = int(cand[i][j])
182            path.append(pred)
183        top1 = (cand.gather(-1, unary.argmax(-1, keepdim=True))[:, 0] if logits is None else logits.argmax(-1)).tolist()
184        self.last_probs = probs
185        return path, top1
186
187
188def read_taps(path):
189    f = open(path, "rb")
190    magic, ver, N, nt = struct.unpack("<4i", f.read(16))
191    assert magic == 0x50415453 and ver == 1, (hex(magic), ver)
192    layers = struct.unpack("<%di" % nt, f.read(4 * nt))
193    rec = 8 + 4 * nt * N
194    data = f.read()
195    n = len(data) // rec
196    pos = np.empty(n, np.int32)
197    tok = np.empty(n, np.int32)
198    taps = np.empty((n, nt * N), np.float32)
199    for i in range(n):
200        o = i * rec
201        pos[i], tok[i] = struct.unpack_from("<2i", data, o)
202        taps[i] = np.frombuffer(data, np.float32, nt * N, o + 8)
203    return layers, pos, tok, taps