okami.mom/strata

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

Niko1221Merge f-own-5b 9b242bb5b into f-own-int (round 15: the own text encoder and tokenizer as test programs, the DiT reference tool and position tables; committed work only)11c8c701a

main
26.5 KiB604 linesraw
1"""tools/image/gate/te_ref.py - TEST-ONLY (OWN-5 gate harness): a numpy reference of Qwen-Image-2.1's text encoder as
2stable-diffusion.cpp 2988060 runs it for one prompt (src/conditioning/conditioner.hpp LLMEmbedder, VERSION_QWEN_IMAGE_2_1;
3src/model/te/llm.hpp, LLMArch::QWEN3_VL, text only).
4
5It is the oracle for our own GPU text encoder (step 3): the tokens, the per-layer activation ranges (what must fit the
6f16 operands of the GEMMs), and the f32 condition our encoder is measured against besides sd.cpp's own (cond.bin of
7run_set.py --dump).
8
9What sd.cpp computes (read from the pinned tree, 11-11):
10  prompt   = "<|im_start|>system\\nComprehend and analyze the provided prompt.<|im_end|>\\n" + "<|im_start|>user\\n"
11             + (text or " ") + "<|im_end|>\\n<|im_start|>assistant\\n"
12  tokens   = Qwen2 byte-level BPE (sd.cpp's own vocab: 256 bytes + merges in order + 31 special literals), the prompt
13             split into [prefix | parse_prompt_attention(text) pieces | suffix], each piece encoded on its own;
14             a piece's weight is its attention weight ("(word:1.2)" syntax), 1.0 for plain text
15  model    = Qwen3-VL-8B text model: 36 layers, hidden 4096, 32 query heads / 8 KV heads of 128, FFN 12288 (SwiGLU),
16             RMSNorm eps 1e-6 before attention and FFN, per-head RMSNorm on q and k (q_norm / k_norm), rope on q and k
17             after the norms (ggml IMROPE, sections 24/20/20, base 5e6; with text-only positions t = h = w = i it is the
18             plain NEOX rotation of halves), causal attention, scale 1/sqrt(128), no bias anywhere
19  output   = the residual stream after layer 36 WITHOUT the final norm (out_layers = {36}), times the token weights
20             (apply_token_weights; identity for plain text), minus the system tokens (prompt_template_encode_start_idx
21             = the system prefix's token count)
22  cond     = float32 [n_tokens - n_system, 4096]
23
24Two arithmetic modes:
25  "f32"    weights dequantized exactly to f32 (the GGUF block formats, f32 maths in ggml's order), every GEMM and the
26           attention in float64 rounded to float32, the rest float32.  The "ideal" condition.
27  "f16op"  what our GPU encoder computes: weights f32 -> f16 (round to nearest even), GEMM inputs rounded to f16,
28           the products accumulated exactly (float64; the GPU accumulates in f32), Q / K / V rounded to f16, scores f32,
29           probabilities rounded to f16 before P.V; the rest float32.
30
31    python -I -B te_ref.py <te.gguf> --out-dir D [--prompts 0-7 | --prompt-file F] [--mode f32,f16op]
32                           [--cmp NAME=/path/dump_p{p}_s42/cond.bin ...] [--stats]
33        writes D/cond_p<p>_<mode>.npy (float32 [n, 4096]), D/tokens_p<p>.json, D/te_ref.json (comparisons, ranges)
34    python -I -B te_ref.py <te.gguf> --tokens "some text"          the token ids sd.cpp would build, and n_system
35    --tokens-from /path/dump_p{p}_s42   compare the ids with sd.cpp's own (stage_hooks.py tokens.bin / tokens.start)"""
36from __future__ import annotations
37
38import argparse
39import json
40import math
41import re
42import sys
43import time
44from pathlib import Path
45
46import numpy as np
47
48_HERE = Path(__file__).resolve().parent
49for _p in (_HERE, _HERE.parents[1]):          # tools/image/gate, tools (gguf_reader.py)
50    if str(_p) not in sys.path:
51        sys.path.insert(0, str(_p))
52from gguf_reader import GGUFFile  # noqa: E402
53
54SYSTEM = "<|im_start|>system\nComprehend and analyze the provided prompt.<|im_end|>\n"
55USER = "<|im_start|>user\n"
56SUFFIX = "<|im_end|>\n<|im_start|>assistant\n"
57# sd.cpp tokenizers/qwen2_tokenizer.cpp qwen2_special_tokens(): ids 151643 + index (after 256 bytes + 151387 merges)
58SPECIALS = ["<|endoftext|>", "<|im_start|>", "<|im_end|>", "<|object_ref_start|>", "<|object_ref_end|>", "<|box_start|>",
59            "<|box_end|>", "<|quad_start|>", "<|quad_end|>", "<|vision_start|>", "<|vision_end|>", "<|vision_pad|>",
60            "<|image_pad|>", "<|video_pad|>", "<tool_call>", "</tool_call>", "<|fim_prefix|>", "<|fim_middle|>",
61            "<|fim_suffix|>", "<|fim_pad|>", "<|repo_name|>", "<|file_sep|>", "<tool_response>", "</tool_response>",
62            "<think>", "</think>", "<|boi_token|>", "<|bor_token|>", "<|eor_token|>", "<|bot_token|>", "<|tms_token|>"]
63QWEN2_SPLIT = r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"""
64F16_MAX = 65504.0
65F16_MIN_NORMAL = 6.103515625e-05
66KV_IQ4NL = np.array([-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113], dtype=np.float32)
67
68
69# ------------------------------------------------------------------ GGUF block formats -> f32 (ggml-quants.c order of operations)
70def _f16(b: np.ndarray) -> np.ndarray:
71    return np.ascontiguousarray(b).view("<f2").astype(np.float32).reshape(b.shape[0])
72
73
74def _scale_min_k4(s: np.ndarray):
75    """get_scale_min_k4 for j = 0..7 over [nb, 12] scale bytes -> (sc [nb, 8], m [nb, 8]) as float32."""
76    s = s.astype(np.int32)
77    sc = np.empty((s.shape[0], 8), np.int32)
78    mn = np.empty((s.shape[0], 8), np.int32)
79    sc[:, :4] = s[:, 0:4] & 63
80    mn[:, :4] = s[:, 4:8] & 63
81    sc[:, 4:] = (s[:, 8:12] & 0x0F) | ((s[:, 0:4] >> 6) << 4)
82    mn[:, 4:] = (s[:, 8:12] >> 4) | ((s[:, 4:8] >> 6) << 4)
83    return sc.astype(np.float32), mn.astype(np.float32)
84
85
86def deq_q4_k(raw: np.ndarray) -> np.ndarray:
87    b = raw.reshape(-1, 144)
88    d, dmin = _f16(b[:, 0:2]), _f16(b[:, 2:4])
89    sc, mn = _scale_min_k4(b[:, 4:16])
90    qs = b[:, 16:144].reshape(-1, 4, 32)
91    dl = d[:, None] * sc                      # d1 = d * sc  (f32)
92    ml = dmin[:, None] * mn                   # m1 = dmin * m
93    lo = (qs & 0x0F).astype(np.float32)
94    hi = (qs >> 4).astype(np.float32)
95    y = np.empty((b.shape[0], 4, 2, 32), np.float32)
96    y[:, :, 0] = dl[:, 0::2, None] * lo - ml[:, 0::2, None]
97    y[:, :, 1] = dl[:, 1::2, None] * hi - ml[:, 1::2, None]
98    return y.reshape(-1)
99
100
101def deq_q5_k(raw: np.ndarray) -> np.ndarray:
102    b = raw.reshape(-1, 176)
103    d, dmin = _f16(b[:, 0:2]), _f16(b[:, 2:4])
104    sc, mn = _scale_min_k4(b[:, 4:16])
105    qh = b[:, 16:48]                          # [nb, 32]
106    ql = b[:, 48:176].reshape(-1, 4, 32)
107    dl = d[:, None] * sc
108    ml = dmin[:, None] * mn
109    y = np.empty((b.shape[0], 4, 2, 32), np.float32)
110    for g in range(4):
111        u1, u2 = 1 << (2 * g), 2 << (2 * g)
112        lo = ((ql[:, g] & 0x0F) + np.where(qh & u1, 16, 0)).astype(np.float32)
113        hi = ((ql[:, g] >> 4) + np.where(qh & u2, 16, 0)).astype(np.float32)
114        y[:, g, 0] = dl[:, 2 * g, None] * lo - ml[:, 2 * g, None]
115        y[:, g, 1] = dl[:, 2 * g + 1, None] * hi - ml[:, 2 * g + 1, None]
116    return y.reshape(-1)
117
118
119def deq_q6_k(raw: np.ndarray) -> np.ndarray:
120    b = raw.reshape(-1, 210)
121    ql, qh = b[:, 0:128].astype(np.int32), b[:, 128:192].astype(np.int32)
122    sc = b[:, 192:208].view(np.int8).astype(np.float32)
123    d = _f16(b[:, 208:210])
124    y = np.empty((b.shape[0], 2, 4, 32), np.float32)
125    for h in range(2):
126        L, H = ql[:, 64 * h:64 * h + 64], qh[:, 32 * h:32 * h + 32]
127        q = [((L[:, 0:32] & 0xF) | (((H >> 0) & 3) << 4)) - 32, ((L[:, 32:64] & 0xF) | (((H >> 2) & 3) << 4)) - 32,
128             ((L[:, 0:32] >> 4) | (((H >> 4) & 3) << 4)) - 32, ((L[:, 32:64] >> 4) | (((H >> 6) & 3) << 4)) - 32]
129        for k in range(4):
130            # y = d * (float)sc[is + 2k] * (float)q, is = l / 16
131            s = np.repeat(sc[:, 8 * h + 2 * k:8 * h + 2 * k + 2], 16, axis=1)       # [nb, 32]
132            y[:, h, k] = (d[:, None] * s) * q[k].astype(np.float32)
133    return y.reshape(-1)
134
135
136def deq_iq4_xs(raw: np.ndarray) -> np.ndarray:
137    b = raw.reshape(-1, 136)
138    d = _f16(b[:, 0:2])
139    sh = b[:, 2:4].copy().view("<u2").astype(np.int32).reshape(-1)
140    sl = b[:, 4:8].astype(np.int32)
141    qs = b[:, 8:136].reshape(-1, 8, 16)
142    y = np.empty((b.shape[0], 8, 2, 16), np.float32)
143    for ib in range(8):
144        ls = ((sl[:, ib // 2] >> (4 * (ib % 2))) & 0x0F) | (((sh >> (2 * ib)) & 3) << 4)
145        dl = d * (ls - 32).astype(np.float32)
146        y[:, ib, 0] = dl[:, None] * KV_IQ4NL[qs[:, ib] & 0x0F]
147        y[:, ib, 1] = dl[:, None] * KV_IQ4NL[qs[:, ib] >> 4]
148    return y.reshape(-1)
149
150
151def deq_q8_0(raw: np.ndarray) -> np.ndarray:
152    b = raw.reshape(-1, 34)
153    return (_f16(b[:, 0:2])[:, None] * b[:, 2:34].view(np.int8).astype(np.float32)).reshape(-1)
154
155
156DEQ = {"Q4_K": deq_q4_k, "Q5_K": deq_q5_k, "Q6_K": deq_q6_k, "IQ4_XS": deq_iq4_xs, "Q8_0": deq_q8_0,
157       "F32": lambda r: r.view("<f4").astype(np.float32), "F16": lambda r: r.view("<f2").astype(np.float32),
158       "BF16": lambda r: (r.view("<u2").astype(np.uint32) << 16).view(np.float32)}
159
160
161class Weights:
162    def __init__(self, path: Path):
163        self.g = GGUFFile(path)
164        self.t = {t.name: t for t in self.g.tensors}
165        self.mm = np.memmap(path, dtype=np.uint8, mode="r")
166        md = self.g.metadata
167        self.n_layer = int(md["qwen3vl.block_count"])
168        self.n_embd = int(md["qwen3vl.embedding_length"])
169        self.n_ff = int(md["qwen3vl.feed_forward_length"])
170        self.n_head = int(md["qwen3vl.attention.head_count"])
171        self.n_kv = int(md["qwen3vl.attention.head_count_kv"])
172        self.hd = int(md["qwen3vl.attention.key_length"])
173        self.theta = float(md["qwen3vl.rope.freq_base"])
174        self.eps = 1e-6                                   # llm.hpp config.rms_norm_eps for QWEN3_VL (f32 1e-6f)
175
176    def raw(self, name: str, row0: int = 0, rows: int | None = None) -> tuple[np.ndarray, list[int], str]:
177        t = self.t[name]
178        ne0 = t.shape[0]
179        nrow = t.elements // ne0
180        rb = t.expected_bytes() // nrow
181        rows = nrow - row0 if rows is None else rows
182        a = self.g.data_start + t.offset + row0 * rb
183        return np.asarray(self.mm[a:a + rows * rb]), [ne0, rows], t.type_name
184
185    def mat(self, name: str, row0: int = 0, rows: int | None = None) -> np.ndarray:
186        """float32 [rows, ne0] (the GGUF's ne1 = output features, ne0 = input features)."""
187        r, (ne0, n), ty = self.raw(name, row0, rows)
188        return DEQ[ty](r).reshape(n, ne0)
189
190
191# ------------------------------------------------------------------ tokens (sd.cpp's Qwen2Tokenizer + parse_prompt_attention)
192def bytes_to_unicode() -> dict[int, str]:
193    bs = list(range(0x21, 0x7F)) + list(range(0xA1, 0xAD)) + list(range(0xAE, 0x100))
194    cs = bs[:]
195    n = 0
196    for b in range(256):
197        if b not in bs:
198            bs.append(b)
199            cs.append(256 + n)
200            n += 1
201    return {b: chr(c) for b, c in zip(bs, cs)}
202
203
204class Qwen2Tok:
205    def __init__(self, merges: list[str]):
206        import regex
207        bu = bytes_to_unicode()
208        self.byte_enc = bu
209        # sd.cpp load_from_merges: tokens = the 256 byte characters in bytes_to_unicode() ORDER, then merges, then specials
210        order = list(range(0x21, 0x7F)) + list(range(0xA1, 0xAD)) + list(range(0xAE, 0x100))
211        order += [b for b in range(256) if b not in order]
212        vocab = [bu[b] for b in order]
213        pairs = [tuple(m.split(" ", 1)) for m in merges]
214        vocab += [a + b for a, b in pairs]
215        self.vocab = vocab
216        self.enc = {}
217        for i, tok in enumerate(vocab):
218            self.enc[tok] = i                      # std::map assignment: a later duplicate wins
219        for i, s in enumerate(SPECIALS):
220            self.enc[s] = len(vocab) + i
221        self.ranks = {p: r for r, p in enumerate(pairs)}
222        self.pat = regex.compile(QWEN2_SPLIT)
223
224    def bpe(self, word: str) -> list[str]:
225        w = list(word)
226        if len(w) < 2:
227            return w
228        while True:
229            best, br = None, None
230            for i in range(len(w) - 1):
231                r = self.ranks.get((w[i], w[i + 1]))
232                if r is not None and (br is None or r < br):
233                    best, br = (w[i], w[i + 1]), r
234            if best is None:
235                break
236            a, b = best
237            nw, i = [], 0
238            while i < len(w):
239                if i < len(w) - 1 and w[i] == a and w[i + 1] == b:
240                    nw.append(a + b)
241                    i += 2
242                else:
243                    nw.append(w[i])
244                    i += 1
245            w = nw
246            if len(w) == 1:
247                break
248        return w
249
250    def encode(self, text: str) -> list[int]:
251        out = []
252        for piece in split_with_special_tokens(text, SPECIALS):
253            if piece in SPECIALS:
254                out.append(self.enc[piece])
255                continue
256            for m in self.pat.findall(piece):
257                if not m:
258                    continue
259                u = "".join(self.byte_enc[b] for b in m.encode("utf-8"))
260                out += [self.enc.get(s, 151643) for s in self.bpe(u)]
261        return out
262
263
264def split_with_special_tokens(text: str, specials: list[str]) -> list[str]:
265    res, pos = [], 0
266    while pos < len(text):
267        nxt, tok = len(text), ""
268        for s in specials:
269            p = text.find(s, pos)
270            if p != -1 and (p < nxt or (p == nxt and len(s) > len(tok))):
271                nxt, tok = p, s
272        if nxt > pos:
273            res.append(text[pos:nxt])
274        if tok:
275            res.append(tok)
276            pos = nxt + len(tok)
277        else:
278            break
279    return res
280
281
282_RE_ATT = re.compile(r"\\\(|\\\)|\\\[|\\\]|\\\\|\\|\(|\[|\)|\]|\bBREAK\b|[^\\()\[\]:B]{1,1024}|:|\bB", re.ASCII)
283_RE_BREAK = re.compile(r"\s*\bBREAK\b\s*", re.ASCII)
284SQ = np.float32(1) / np.float32(1.1)                 # square_bracket_multiplier = 1 / 1.1f (float division)
285
286
287def parse_prompt_attention(text: str) -> list[list]:
288    """core/util.cpp parse_prompt_attention (the A1111 syntax), weights as float32 products."""
289    res, rb, sb = [], [], []
290    f32 = np.float32
291
292    def mul(start, m):
293        for p in range(start, len(res)):
294            res[p][1] = f32(res[p][1] * f32(m))
295
296    rest = text
297    while True:
298        m = _RE_ATT.search(rest)
299        if not m:
300            break
301        tok, suffix = m.group(0), rest[m.end():]
302        if tok == ":":
303            mw = re.match(r"([+-]?[0-9.]*)\)", suffix)
304            if mw and mw.group(1) not in ("", "+", "-"):
305                try:
306                    v = float(mw.group(1))
307                    if math.isfinite(v) and mw.group(1).count(".") <= 1 and mw.group(1) not in (".", "+.", "-."):
308                        if rb:
309                            mul(rb.pop(), v)
310                        rest = suffix[mw.end():]
311                        continue
312                except ValueError:
313                    pass
314        if tok == "(":
315            rb.append(len(res))
316        elif tok == "[":
317            sb.append(len(res))
318        elif tok == ")" and rb:
319            mul(rb.pop(), 1.1)
320        elif tok == "]" and sb:
321            mul(sb.pop(), SQ)
322        elif tok == "\\(":
323            res.append([tok[1:], f32(1.0)])
324        elif _RE_BREAK.search(tok):
325            res.append(["BREAK", f32(-1.0)])
326        else:
327            res.append([tok, f32(1.0)])
328        rest = suffix
329    for p in rb:
330        mul(p, 1.1)
331    for p in sb:
332        mul(p, SQ)
333    if not res:
334        res.append(["", f32(1.0)])
335    i = 0
336    while i + 1 < len(res):
337        if res[i][1] == res[i + 1][1]:
338            res[i][0] += res[i + 1][0]
339            del res[i + 1]
340        else:
341            i += 1
342    return res
343
344
345def build_tokens(tok: Qwen2Tok, text: str) -> tuple[list[int], list[float], int]:
346    """LLMEmbedder::get_learned_condition (VERSION_QWEN_IMAGE_2_1, no reference images) + tokenize(): ids, weights,
347    n_system (prompt_template_encode_start_idx)."""
348    n_sys = len(tok.encode(SYSTEM))
349    body = text if text else " "
350    pieces = [[SYSTEM + USER, np.float32(1.0)]] + parse_prompt_attention(body) + [[SUFFIX, np.float32(1.0)]]
351    ids, w = [], []
352    for s, wt in pieces:
353        t = tok.encode(s)
354        ids += t
355        w += [float(wt)] * len(t)
356    return ids, w, n_sys
357
358
359# ------------------------------------------------------------------ the model
360def f16r(x: np.ndarray) -> np.ndarray:
361    return x.astype(np.float16).astype(np.float32)
362
363
364def rmsnorm(x: np.ndarray, w: np.ndarray, eps: float) -> np.ndarray:
365    ms = (x.astype(np.float64) ** 2).mean(-1, keepdims=True)
366    return ((x.astype(np.float64) / np.sqrt(ms + np.float64(np.float32(eps)))).astype(np.float32) * w).astype(np.float32)
367
368
369def rope_neox(x: np.ndarray, theta: float) -> np.ndarray:
370    """x [T, H, D]; NEOX: pairs (i, i + D/2), angle pos * theta^(-2i/D)."""
371    T, H, D = x.shape
372    i = np.arange(D // 2, dtype=np.float64)
373    ang = np.arange(T, dtype=np.float64)[:, None] * theta ** (-2.0 * i / D)[None, :]
374    c, s = np.cos(ang)[:, None, :], np.sin(ang)[:, None, :]
375    a, b = x[..., :D // 2].astype(np.float64), x[..., D // 2:].astype(np.float64)
376    return np.concatenate([a * c - b * s, a * s + b * c], -1).astype(np.float32)
377
378
379def gemm(x: np.ndarray, W64: np.ndarray, f16: bool) -> np.ndarray:
380    xi = f16r(x) if f16 else x
381    return (xi.astype(np.float64) @ W64.T).astype(np.float32)
382
383
384def _rng(stats, key, x):
385    if stats is None:
386        return
387    a = np.abs(x)
388    s = stats.setdefault(key, {"max": 0.0, "n": 0, "over_f16": 0, "subnormal": 0})
389    s["max"] = max(s["max"], float(a.max()))
390    s["n"] += int(a.size)
391    s["over_f16"] += int((a > F16_MAX).sum())
392    s["subnormal"] += int(((a > 0) & (a < F16_MIN_NORMAL)).sum())
393
394
395class Layer:
396    def __init__(self, W: Weights, i: int, f16: bool):
397        p = f"blk.{i}."
398        conv = (lambda a: f16r(a).astype(np.float64)) if f16 else (lambda a: a.astype(np.float64))
399        self.attn_norm = W.mat(p + "attn_norm.weight").reshape(-1)
400        self.ffn_norm = W.mat(p + "ffn_norm.weight").reshape(-1)
401        self.qn = W.mat(p + "attn_q_norm.weight").reshape(-1)
402        self.kn = W.mat(p + "attn_k_norm.weight").reshape(-1)
403        self.q, self.k, self.v = (conv(W.mat(p + f"attn_{n}.weight")) for n in "qkv")
404        self.o = conv(W.mat(p + "attn_output.weight"))
405        self.g, self.u, self.d = (conv(W.mat(p + f"ffn_{n}.weight")) for n in ("gate", "up", "down"))
406
407
408def layer_forward(W: Weights, L: Layer, x: np.ndarray, f16: bool, stats: dict | None, li: int) -> np.ndarray:
409    T = x.shape[0]
410    H, KV, D = W.n_head, W.n_kv, W.hd
411    h = rmsnorm(x, L.attn_norm, W.eps)
412    _rng(stats, f"{li}.attn_in", h)
413    q = gemm(h, L.q, f16).reshape(T, H, D)
414    k = gemm(h, L.k, f16).reshape(T, KV, D)
415    v = gemm(h, L.v, f16).reshape(T, KV, D)
416    q = rope_neox(rmsnorm(q, L.qn, W.eps), W.theta)
417    k = rope_neox(rmsnorm(k, L.kn, W.eps), W.theta)
418    _rng(stats, f"{li}.q", q)
419    _rng(stats, f"{li}.k", k)
420    _rng(stats, f"{li}.v", v)
421    if f16:
422        q, k, v = f16r(q), f16r(k), f16r(v)
423    scale = 1.0 / math.sqrt(D)
424    mask = np.triu(np.full((T, T), -np.inf), 1)
425    out = np.empty((T, H, D), np.float32)
426    rep = H // KV
427    for hh in range(H):
428        kv = hh // rep                                     # ggml broadcast: q head i uses kv head i / (H / KV)
429        s = (q[:, hh].astype(np.float64) @ k[:, kv].astype(np.float64).T)
430        s = (s.astype(np.float32) * np.float32(scale)).astype(np.float64) if f16 else s * scale
431        s = s + mask
432        s = s - s.max(-1, keepdims=True)
433        p = np.exp(s)
434        p = p / p.sum(-1, keepdims=True)
435        if f16:
436            p = f16r(p.astype(np.float32)).astype(np.float64)
437        out[:, hh] = (p @ v[:, kv].astype(np.float64)).astype(np.float32)
438    a = out.reshape(T, H * D)
439    _rng(stats, f"{li}.o_in", a)
440    x = (x + gemm(a, L.o, f16)).astype(np.float32)
441    h = rmsnorm(x, L.ffn_norm, W.eps)
442    _rng(stats, f"{li}.ffn_in", h)
443    g = gemm(h, L.g, f16)
444    u = gemm(h, L.u, f16)
445    a = ((g / (1.0 + np.exp(-g.astype(np.float64)))).astype(np.float32) * u).astype(np.float32)
446    _rng(stats, f"{li}.down_in", a)
447    x = (x + gemm(a, L.d, f16)).astype(np.float32)
448    _rng(stats, f"{li}.resid", x)
449    return x
450
451
452def embed(W: Weights, ids: list[int]) -> np.ndarray:
453    return np.stack([W.mat("token_embd.weight", i, 1)[0] for i in ids]).astype(np.float32)
454
455
456def apply_token_weights(h: np.ndarray, w: list[float]) -> np.ndarray:
457    wa = np.asarray(w, np.float32)
458    if np.all(wa == 1.0):
459        return h
460    m0 = np.float32(h.astype(np.float64).mean())
461    h = (h * wa[:, None]).astype(np.float32)
462    m1 = np.float32(h.astype(np.float64).mean())
463    return (h * np.float32(m0 / m1)).astype(np.float32)
464
465
466# ------------------------------------------------------------------ comparison
467def compare(a: np.ndarray, b: np.ndarray) -> dict:
468    a64, b64 = a.astype(np.float64).reshape(-1), b.astype(np.float64).reshape(-1)
469    ma, mb = a.astype(np.float64), b.astype(np.float64)
470    tc = (ma * mb).sum(1) / np.maximum(np.linalg.norm(ma, axis=1) * np.linalg.norm(mb, axis=1), 1e-30)
471    return {"identical": bool(np.array_equal(a, b)), "max_abs": float(np.abs(a64 - b64).max()),
472            "rel_l2": float(np.linalg.norm(a64 - b64) / max(np.linalg.norm(b64), 1e-30)),
473            "cos": float(a64 @ b64 / max(np.linalg.norm(a64) * np.linalg.norm(b64), 1e-30)),
474            "token_cos_min": float(tc.min()), "token_cos_mean": float(tc.mean())}
475
476
477def load_cond(path: str) -> np.ndarray:
478    p = Path(path)
479    shape = [int(x) for x in p.with_suffix(".shape").read_text().split()]
480    return np.fromfile(p, dtype="<f4").reshape(shape[1], shape[0])
481
482
483def prompt_list(spec: str) -> list[int]:
484    out = []
485    for part in spec.split(","):
486        if "-" in part:
487            a, b = part.split("-")
488            out += list(range(int(a), int(b) + 1))
489        else:
490            out.append(int(part))
491    return out
492
493
494def main(argv=None) -> int:
495    ap = argparse.ArgumentParser()
496    ap.add_argument("gguf")
497    ap.add_argument("--out-dir")
498    ap.add_argument("--prompts", default="0-7")
499    ap.add_argument("--prompt-file", action="append", default=[])
500    ap.add_argument("--mode", default="f32,f16op")
501    ap.add_argument("--cmp", action="append", default=[], help="NAME=path with {p} for the prompt index")
502    ap.add_argument("--tokens")
503    ap.add_argument("--tokens-from", help="sd.cpp's stage dump dir with {p} (tokens.bin, tokens.start): ids must match")
504    ap.add_argument("--stats", action="store_true")
505    ap.add_argument("--layers", type=int, default=0, help="debug: stop after this many layers")
506    a = ap.parse_args(argv)
507    W = Weights(Path(a.gguf))
508    tok = Qwen2Tok(W.g.metadata["tokenizer.ggml.merges"])
509    gv = W.g.metadata["tokenizer.ggml.tokens"]
510    diff = sum(1 for x, y in zip(tok.vocab, gv) if x != y)
511    spec = sum(1 for i, s in enumerate(SPECIALS) if len(gv) > len(tok.vocab) + i and gv[len(tok.vocab) + i] != s)
512    print(f"vocab: sd.cpp construction {len(tok.vocab)} + {len(SPECIALS)} specials; differs from the GGUF's list at "
513          f"{diff} regular and {spec} special ids", file=sys.stderr)
514    if a.tokens is not None:
515        ids, w, n_sys = build_tokens(tok, a.tokens)
516        print(json.dumps({"ids": ids, "weights": w, "n_system": n_sys}))
517        return 0
518    from run_set import PROMPTS
519    texts = {}
520    if a.prompt_file:
521        for i, f in enumerate(a.prompt_file):
522            texts[i] = Path(f).read_text(encoding="utf-8")
523    else:
524        for i in prompt_list(a.prompts):
525            texts[i] = PROMPTS[i]
526    out = Path(a.out_dir)
527    out.mkdir(parents=True, exist_ok=True)
528    modes = a.mode.split(",")
529    toks = {}
530    for i, t in texts.items():
531        ids, w, n_sys = build_tokens(tok, t)
532        toks[i] = (ids, w, n_sys)
533        if a.tokens_from:
534            d = Path(a.tokens_from.replace("{p}", str(i)))
535            sd_ids = np.fromfile(d / "tokens.bin", dtype="<i4").tolist()
536            sd_start = int((d / "tokens.start").read_text().split()[0])
537            same = sd_ids == ids and sd_start == n_sys
538            print(f"p{i}: TOKENS {'IDENTICAL' if same else 'DIFFER'} to sd.cpp ({len(sd_ids)} ids, start {sd_start})")
539            if not same:
540                return 3
541        (out / f"tokens_p{i}.json").write_text(json.dumps({"text": t, "ids": ids, "weights": w, "n_system": n_sys}))
542        print(f"p{i}: {len(ids)} tokens, n_system {n_sys}, cond rows {len(ids) - n_sys}", flush=True)
543    xs = {(i, m): embed(W, toks[i][0]) for i in texts for m in modes}
544    stats = {m: {} for m in modes} if a.stats else None
545    nl = a.layers or W.n_layer
546    t0 = time.time()
547    for li in range(nl):
548        for m in modes:
549            L = Layer(W, li, m == "f16op")
550            for i in texts:
551                xs[(i, m)] = layer_forward(W, L, xs[(i, m)], m == "f16op", stats[m] if stats else None, li)
552            del L
553        print(f"layer {li} done {time.time() - t0:.0f} s", flush=True)
554    res = {"prompts": {}, "modes": modes, "layers": nl}
555    conds = {}
556    for i in texts:
557        ids, w, n_sys = toks[i]
558        r = {"n_tokens": len(ids), "n_system": n_sys}
559        for m in modes:
560            c = apply_token_weights(xs[(i, m)], w)[n_sys:]
561            conds[(i, m)] = c
562            np.save(out / f"cond_p{i}_{m}.npy", c)
563        if "f32" in modes and "f16op" in modes:
564            r["f16op_vs_f32"] = compare(conds[(i, "f16op")], conds[(i, "f32")])
565        for spec in a.cmp:
566            name, path = spec.split("=", 1)
567            pth = path.replace("{p}", str(i))
568            if not Path(pth).is_file():
569                continue
570            ref = load_cond(pth)
571            if ref.shape != conds[(i, modes[0])].shape:
572                r[f"{name}_shape"] = [list(ref.shape), list(conds[(i, modes[0])].shape)]
573                continue
574            for m in modes:
575                r[f"{name}_vs_{m}"] = compare(ref, conds[(i, m)])
576        res["prompts"][str(i)] = r
577        print(f"p{i}: " + json.dumps({k: (v if not isinstance(v, dict) else {kk: round(vv, 6) if isinstance(vv, float) else vv for kk, vv in v.items()}) for k, v in r.items()}), flush=True)
578    # summaries per comparison
579    keys = sorted({k for r in res["prompts"].values() for k, v in r.items() if isinstance(v, dict)})
580    summ = {}
581    for k in keys:
582        rows = [r[k] for r in res["prompts"].values() if k in r]
583        summ[k] = {"n": len(rows), "rel_l2_mean": float(np.mean([x["rel_l2"] for x in rows])),
584                   "rel_l2_max": max(x["rel_l2"] for x in rows), "cos_min": min(x["cos"] for x in rows),
585                   "token_cos_min": min(x["token_cos_min"] for x in rows), "max_abs": max(x["max_abs"] for x in rows),
586                   "identical": sum(x["identical"] for x in rows)}
587        print(f"SUMMARY {k}: {json.dumps(summ[k])}")
588    res["summary"] = summ
589    if stats:
590        res["ranges"] = stats
591        for m in modes:
592            kinds = sorted({k.split(".", 1)[1] for k in stats[m]})
593            for kd in kinds:
594                vals = [(int(k.split(".")[0]), v) for k, v in stats[m].items() if k.split(".", 1)[1] == kd]
595                top = max(vals, key=lambda t: t[1]["max"])
596                sub = sum(v["subnormal"] for _, v in vals) / max(sum(v["n"] for _, v in vals), 1)
597                over = sum(v["over_f16"] for _, v in vals)
598                print(f"RANGE {m} {kd}: max {top[1]['max']:.4g} at layer {top[0]}, over f16 {over}, subnormal share {sub:.2e}")
599    (out / "te_ref.json").write_text(json.dumps(res, indent=1))
600    return 0
601
602
603if __name__ == "__main__":
604    sys.exit(main())