okami.mom/strata

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

Niko1221Merge f-own-5b adfcf9028 into f-own-int (round 16: the strata-image test program and its parts, DiT runner, sampler, noise, PNG writer; hooked into no build)e4309aaf3

main
21.2 KiB433 linesraw
1"""tools/image/gate/dit_ref.py - TEST-ONLY (OWN-5 gate harness): a numpy reference of one Qwen-Image-2.1 DiT call as
2stable-diffusion.cpp 2988060 computes it (src/model/diffusion/qwen_image_2_1.hpp, QwenImage21Runner, no reference
3pictures, text prefix + image tokens in one sequence), from the stage-hook dumps of that call: the latent and the
4timestep it got (dit_x_<k>, dit_t_<k>) and the condition (cond).  The oracle of step 4 (our own DiT GEMMs and runner).
5
6The model (read from the pinned tree):
7  time   = [t, 0] -> sinusoid 256 (cos half, then sin half; freq = exp(-ln 10000 * j / 128)) -> linear_1 -> SiLU ->
8           linear_2 -> SiLU;  mod = modulation.1(time) -> 4 chunks m0..m3 of 4096, row 0 for image tokens, row 1 (t = 0)
9           for text tokens;  scale = norm_out.linear(time row 0)
10  text   = txt_in: RMSNorm(eps 1e-6) x (1 + w) -> in_layer -> GELU (tanh form) -> out_layer;  image = img_in(latent
11           tokens, patch 1, token h*W + w);  joint = [text ; image]
12  block  = h = LN(x) (1 + m0);  q k v = h W^T, per-head RMSNorm (norm_q / norm_k, eps 1e-6), RoPE (interleaved pairs,
13           axes 16 / 56 / 56, theta 10000, positions text (p, p, p), image (L, h - (H - H/2), w - (W - W/2)));
14           attention scale 1/sqrt(128): text rows causal over the text, image rows over everything;
15           x += to_out(attn) tanh(m1);  h = LN(x) (1 + m2);  gate | up = h Wgu^T;  x += out(up silu(gate)) tanh(m3)
16  head   = LN(image rows) (1 + scale) -> proj_out -> velocity [64, H, W]
17  (LN: no affine, eps 1e-6; no linear has a bias)
18
19Modes: "f32" (weights dequantized exactly, every GEMM and the attention in float64 rounded to float32) and "f16op"
20(f16 weights and GEMM inputs, exact accumulation, Q / K / V and the probabilities f16) and "f16acc32" (as f16op but
21every GEMM sums in float32, as the GPU does; the stage rule's comparison since 11-11, coordinator: on prompt 5 the
22exact-sum emulation moves 1.6x from inputs 3e-6 apart; the nine-case table: dit_acc32_cases.py).
23
24    python -I -B dit_ref.py <dit.gguf> --dumps D [D ...] [--call 0] [--mode f32,f16op] [--out-dir O]
25                            [--cmp NAME=<file with {dump}>]  e.g. --cmp stock={dump}/vel_0.bin
26        each D is a stage dump dir with dit_x_<call>, dit_t_<call>, cond; writes O/<dump name>_<mode>.npy"""
27from __future__ import annotations
28
29import argparse
30import json
31import math
32import sys
33import time
34from pathlib import Path
35
36import numpy as np
37
38_HERE = Path(__file__).resolve().parent
39for _p in (_HERE, _HERE.parents[1]):
40    if str(_p) not in sys.path:
41        sys.path.insert(0, str(_p))
42from gguf_reader import GGUFFile  # noqa: E402
43from te_ref import DEQ, compare, f16r  # noqa: E402
44
45PFX = "model.diffusion_model."
46AXES = (16, 56, 56)
47F32 = np.float32
48
49
50class DitWeights:
51    def __init__(self, path: Path):
52        self.g = GGUFFile(path)
53        self.t = {t.name: t for t in self.g.tensors}
54        self.mm = np.memmap(path, dtype=np.uint8, mode="r")
55        self.n_layer = 1 + max(int(n[len(PFX + "transformer_blocks."):].split(".")[0]) for n in self.t
56                               if n.startswith(PFX + "transformer_blocks."))
57
58    def mat(self, name: str) -> np.ndarray:
59        t = self.t[PFX + name]
60        a = self.g.data_start + t.offset
61        r = np.asarray(self.mm[a:a + t.expected_bytes()])
62        ne0 = t.shape[0]
63        return DEQ[t.type_name](r).reshape(-1, ne0)
64
65
66# ------------------------------------------------------------------ positions and RoPE (Rope::embed_nd, QwenImage21Layout)
67def layout_positions(text_len: int, H: int, W: int) -> np.ndarray:
68    pos = [[float(p)] * 3 for p in range(text_len)]
69    for h in range(H):
70        for w in range(W):
71            pos.append([float(text_len), float(h - (H - H // 2)), float(w - (W - W // 2))])
72    return np.asarray(pos, dtype=F32)
73
74
75def rope_table(pos: np.ndarray, theta: float = 10000.0) -> tuple[np.ndarray, np.ndarray]:
76    """cos, sin [n, 64] in the order sd.cpp concatenates the axes (axis 0: 8 pairs, axis 1 and 2: 28 each)."""
77    cs, sn = [], []
78    for ax, dim in enumerate(AXES):
79        half = dim // 2
80        start, end = F32(0), F32((dim * 1.0 - 2) / dim)
81        step = F32((end - start) / F32(half - 1))
82        scale = np.array([F32(start + F32(i) * step) for i in range(half)], dtype=F32)
83        omega = (F32(1.0) / np.power(F32(theta), scale).astype(F32)).astype(F32)
84        ang = (pos[:, ax:ax + 1].astype(F32) * omega[None, :]).astype(F32)
85        cs.append(np.cos(ang).astype(F32))
86        sn.append(np.sin(ang).astype(F32))
87    return np.concatenate(cs, 1), np.concatenate(sn, 1)
88
89
90def apply_rope(x: np.ndarray, c: np.ndarray, s: np.ndarray) -> np.ndarray:
91    """x [n, H, 128]; interleaved pairs (2j, 2j+1): [[cos, -sin], [sin, cos]]."""
92    a = x[..., 0::2].astype(np.float64)
93    b = x[..., 1::2].astype(np.float64)
94    cc, ss = c[:, None, :].astype(np.float64), s[:, None, :].astype(np.float64)
95    out = np.empty(x.shape, np.float64)
96    out[..., 0::2] = a * cc - b * ss
97    out[..., 1::2] = a * ss + b * cc
98    return out.astype(F32)
99
100
101# ------------------------------------------------------------------ pieces
102def layer_norm(x):
103    x64 = x.astype(np.float64)
104    m = x64.mean(-1, keepdims=True)
105    v = ((x64 - m) ** 2).mean(-1, keepdims=True)
106    return ((x64 - m) / np.sqrt(v + 1e-6)).astype(F32)
107
108
109def rms_norm(x, w):
110    x64 = x.astype(np.float64)
111    return ((x64 / np.sqrt((x64 ** 2).mean(-1, keepdims=True) + np.float64(F32(1e-6)))).astype(F32) * w).astype(F32)
112
113
114def gelu_tanh(x):
115    x64 = x.astype(np.float64)
116    return (0.5 * x64 * (1.0 + np.tanh(0.7978845608028654 * x64 * (1.0 + 0.044715 * x64 * x64)))).astype(F32)
117
118
119def silu(x):
120    x64 = x.astype(np.float64)
121    return (x64 / (1.0 + np.exp(-x64))).astype(F32)
122
123
124def timestep_embedding(t: np.ndarray, dim: int = 256, max_period: int = 10000) -> np.ndarray:
125    half = dim // 2
126    j = np.arange(half, dtype=np.float64)
127    freq = np.exp(-math.log(max_period) * j / half)
128    arg = t[:, None].astype(np.float64) * freq[None, :]
129    return np.concatenate([np.cos(arg), np.sin(arg)], 1).astype(F32)
130
131
132class Mode:
133    def __init__(self, f16: bool):
134        self.f16 = f16
135
136    def w(self, m: np.ndarray) -> np.ndarray:
137        return (f16r(m) if self.f16 else m).astype(np.float64)
138
139    def gemm(self, x: np.ndarray, W64: np.ndarray) -> np.ndarray:
140        xi = f16r(x) if self.f16 else x
141        return (xi.astype(np.float64) @ W64.T).astype(F32)
142
143
144class ModeAcc32(Mode):
145    """"f16acc32": f16 weights and GEMM inputs, FLOAT32 accumulation (numpy float32 matmul, the BLAS's summation
146    order), as cuBLAS GemmEx with compute 32F sums; everything else as "f16op"."""
147    def __init__(self):
148        super().__init__(True)
149
150    def w(self, m: np.ndarray) -> np.ndarray:
151        return f16r(m).astype(F32)
152
153    def gemm(self, x: np.ndarray, W: np.ndarray) -> np.ndarray:
154        return (f16r(x).astype(F32) @ W.astype(F32, copy=False).T).astype(F32)
155
156
157MODES = ("f32", "f16op", "f16acc32")
158
159
160def make_mode(name: str) -> Mode:
161    if name not in MODES:
162        raise SystemExit(f"dit_ref: unknown mode {name!r} (known: {', '.join(MODES)})")
163    return ModeAcc32() if name == "f16acc32" else Mode(name == "f16op")
164
165
166def attention(q, k, v, L: int, f16: bool) -> np.ndarray:
167    """q k v [n, H, D] (after norms and rope); rows < L (text) causal over the text, the rest over all n."""
168    n, H, D = q.shape
169    if f16:
170        q, k, v = f16r(q), f16r(k), f16r(v)
171    out = np.empty((n, H, D), F32)
172    scale = 1.0 / math.sqrt(D)
173    for h in range(H):
174        s = q[:, h].astype(np.float64) @ k[:, h].astype(np.float64).T
175        s = (s.astype(F32) * F32(scale)).astype(np.float64) if f16 else s * scale
176        s[:L, L:] = -np.inf                                      # text rows see only the text
177        s[:L, :L] += np.triu(np.full((L, L), -np.inf), 1)        # and causally
178        s -= s.max(-1, keepdims=True)
179        p = np.exp(s)
180        p /= p.sum(-1, keepdims=True)
181        if f16:
182            p = f16r(p.astype(F32)).astype(np.float64)
183        out[:, h] = (p @ v[:, h].astype(np.float64)).astype(F32)
184    return out
185
186
187def prelude(Wt: DitWeights, m: Mode, t: float, cond: np.ndarray, x: np.ndarray):
188    tm = timestep_embedding(np.array([t, 0.0], dtype=F32))
189    tm = silu(m.gemm(tm, m.w(Wt.mat("time_text_embed.timestep_embedder.linear_1.weight"))))
190    tm = silu(m.gemm(tm, m.w(Wt.mat("time_text_embed.timestep_embedder.linear_2.weight"))))
191    mod = m.gemm(tm, m.w(Wt.mat("modulation.1.weight")))                  # [2, 4C]
192    scale = m.gemm(tm[:1], m.w(Wt.mat("norm_out.linear.weight")))[0]     # [C]
193    txt = rms_norm(cond, (Wt.mat("txt_in.text_norm.weight").reshape(-1) + F32(1)).astype(F32))
194    txt = gelu_tanh(m.gemm(txt, m.w(Wt.mat("txt_in.in_layer.weight"))))
195    txt = m.gemm(txt, m.w(Wt.mat("txt_in.out_layer.weight")))
196    C, Hh, Ww = x.shape
197    tok = x.reshape(C, Hh * Ww).T.copy()                                  # token h*W + w, channels
198    img = m.gemm(tok, m.w(Wt.mat("img_in.weight")))
199    return mod, scale, np.concatenate([txt, img], 0)
200
201
202def block(Wt: DitWeights, m: Mode, i: int, xj: np.ndarray, rows: np.ndarray, mods, L: int, c, s, wcache=None, mx=None,
203          cap=None):
204    p = f"transformer_blocks.{i}."
205    C = xj.shape[1]
206    H, D = C // 128, 128
207    W = wcache if wcache is not None else {}
208    if not W:
209        for n in ("attn.to_q", "attn.to_k", "attn.to_v", "attn.to_out.0", "img_mlp.gate_up", "img_mlp.out"):
210            W[n] = m.w(Wt.mat(p + n + ".weight"))
211        W["nq"] = Wt.mat(p + "attn.norm_q.weight").reshape(-1)
212        W["nk"] = Wt.mat(p + "attn.norm_k.weight").reshape(-1)
213    m0, m1, m2, m3 = (mods[:, k * C:(k + 1) * C][rows] for k in range(4))   # per token rows
214    h = (layer_norm(xj) * (F32(1) + m0)).astype(F32)
215    n = xj.shape[0]
216    qr, kr = m.gemm(h, W["attn.to_q"]), m.gemm(h, W["attn.to_k"])
217    q = rms_norm(qr.reshape(n, H, D), W["nq"])
218    k = rms_norm(kr.reshape(n, H, D), W["nk"])
219    v = m.gemm(h, W["attn.to_v"]).reshape(n, H, D)
220    q, k = apply_rope(q, c, s), apply_rope(k, c, s)
221    a = attention(q, k, v, L, m.f16).reshape(n, C)
222    if mx is not None:                                   # largest |value| of every GEMM / attention input, text and image rows
223        for nm, arr in (("qkv_in", h), ("q", q), ("k", k), ("v", v), ("to_out_in", a)):
224            mx[f"txt {i} {nm}"] = float(np.abs(arr[:L]).max())
225            mx[f"img {i} {nm}"] = float(np.abs(arr[L:]).max())
226    xj = (xj + (m.gemm(a, W["attn.to_out.0"]) * np.tanh(m1.astype(np.float64)).astype(F32))).astype(F32)
227    h = (layer_norm(xj) * (F32(1) + m2)).astype(F32)
228    if cap is not None:                                   # one block in detail (image rows; K / V over all rows)
229        cap.update(qkv=np.concatenate([qr, kr, v.reshape(n, C)], 1)[L:], q16=q[L:], k16=k, v16=v, att=a[L:],
230                   x_mid=xj[L:].copy(), ln2=h[L:])
231    gu = m.gemm(h, W["img_mlp.gate_up"])
232    F = gu.shape[1] // 2
233    act = (gu[:, F:] * silu(gu[:, :F])).astype(F32)
234    if mx is not None:
235        for nm, arr in (("gate_up_in", h), ("out_in", act)):
236            mx[f"txt {i} {nm}"] = float(np.abs(arr[:L]).max())
237            mx[f"img {i} {nm}"] = float(np.abs(arr[L:]).max())
238    xj = (xj + (m.gemm(act, W["img_mlp.out"]) * np.tanh(m3.astype(np.float64)).astype(F32))).astype(F32)
239    if cap is not None:
240        cap.update(act=act[L:])
241    return xj
242
243
244def head(Wt: DitWeights, m: Mode, xj: np.ndarray, L: int, scale: np.ndarray, Hh: int, Ww: int) -> np.ndarray:
245    img = (layer_norm(xj[L:]) * (F32(1) + scale)).astype(F32)
246    out = m.gemm(img, m.w(Wt.mat("proj_out.weight")))                     # [T, 64]
247    return out.T.reshape(-1, Hh, Ww).astype(F32)
248
249
250TRACE: dict = {}
251MAXIMA: dict = {}
252STATES: dict = {}
253CAPS: dict = {}
254
255
256def trace_cmp(pat: str, d: Path, mode: str, stage: str, parts: dict, normalise: bool = False) -> None:
257    """rel L2 of our run (the trace files) against this mode's value at the same stage, kept in TRACE."""
258    tdir = Path(pat.replace("{name}", d.name))
259    for part, (ref, fname) in parts.items():
260        f = tdir / fname
261        if not f.is_file():
262            continue
263        ours = np.fromfile(f, dtype="<f4").reshape(ref.shape)
264        if normalise:
265            ours = layer_norm(ours)
266        r = compare(ours, ref)
267        TRACE.setdefault((d.name, stage, part), {})[mode] = r["rel_l2"]
268
269
270def load_dump(d: Path, name: str):
271    shape = [int(v) for v in (d / f"{name}.shape").read_text().split()]
272    a = np.fromfile(d / f"{name}.bin", dtype="<f4")
273    return a, shape
274
275
276def main(argv=None) -> int:
277    ap = argparse.ArgumentParser()
278    ap.add_argument("gguf")
279    ap.add_argument("--dumps", nargs="+", required=True)
280    ap.add_argument("--call", type=int, default=0)
281    ap.add_argument("--mode", default="f32,f16op")
282    ap.add_argument("--out-dir")
283    ap.add_argument("--cmp", action="append", default=[])
284    ap.add_argument("--layers", type=int, default=0)
285    ap.add_argument("--trace-block", type=int, default=-1, help="with --trace: compare the inside of this block (image rows)")
286    ap.add_argument("--trace", help="per-stage comparison with a STRATA_DIT_TRACE_DIR dump; {name} = the dump dir name")
287    a = ap.parse_args(argv)
288    Wt = DitWeights(Path(a.gguf))
289    modes = a.mode.split(",")
290    jobs = {}
291    for dd in a.dumps:
292        d = Path(dd)
293        xv, xs = load_dump(d, f"dit_x_{a.call}")
294        tv, _ = load_dump(d, f"dit_t_{a.call}")
295        cv, cs = load_dump(d, "cond")
296        Ww, Hh, C = xs[0], xs[1], xs[2]
297        jobs[d] = {"x": xv.reshape(C, Hh, Ww), "t": float(tv[0]), "cond": cv.reshape(cs[1], cs[0]), "H": Hh, "W": Ww}
298    state = {}
299    t0 = time.time()
300    for mname in modes:
301        m = make_mode(mname)
302        for d, j in jobs.items():
303            mods, scale, xj = prelude(Wt, m, j["t"], j["cond"], j["x"])
304            L = j["cond"].shape[0]
305            c, s = rope_table(layout_positions(L, j["H"], j["W"]))
306            rows = np.array([1] * L + [0] * (xj.shape[0] - L))
307            state[(d, mname)] = [mods, scale, xj, L, c, s, rows]
308            if a.trace:
309                trace_cmp(a.trace, d, mname, "prelude", {"mod": (mods, "mod.bin"), "scale": (scale[None, :], "scale.bin"),
310                                                         "txt_in": (xj[:L], "txtin.bin"), "img_in": (xj[L:], "imgin.bin")})
311    nl = a.layers or Wt.n_layer
312    for i in range(nl):
313        for mname in modes:
314            m = make_mode(mname)
315            wc = {}
316            for d in jobs:
317                st = state[(d, mname)]
318                mx = MAXIMA.setdefault((d.name, mname), {}) if a.trace else None
319                cap = CAPS.setdefault((d.name, mname), {}) if (a.trace and i == a.trace_block) else None
320                st[2] = block(Wt, m, i, st[2], st[6], st[0], st[3], st[4], st[5], wc, mx, cap)
321                if a.trace:
322                    L = st[3]
323                    trace_cmp(a.trace, d, mname, f"block {i:02d}", {"txt": (st[2][:L], f"txt_{i:02d}.bin"),
324                                                                      "img": (st[2][L:], f"img_{i:02d}.bin")})
325                    # what the next step reads of the stream is LayerNorm(x): the same comparison per token-normalised
326                    trace_cmp(a.trace, d, mname, f"block {i:02d}", {"txt LN": (layer_norm(st[2][:L]), f"txt_{i:02d}.bin"),
327                                                                      "img LN": (layer_norm(st[2][L:]), f"img_{i:02d}.bin")},
328                              normalise=True)
329                    STATES[(d.name, mname, i)] = st[2].copy()
330        if a.trace and "f32" in modes and "f16op" in modes:      # the emulation against the reference, same stage
331            for d in jobs:
332                L = state[(d, "f32")][3]
333                for part, sl in (("txt", slice(0, L)), ("img", slice(L, None))):
334                    TRACE.setdefault((d.name, f"block {i:02d}", part), {})["emu_vs_f32"] = \
335                        compare(state[(d, "f16op")][2][sl], state[(d, "f32")][2][sl])["rel_l2"]
336        print(f"block {i} done {time.time() - t0:.0f} s", flush=True)
337    res = {}
338    out = Path(a.out_dir) if a.out_dir else None
339    if out:
340        out.mkdir(parents=True, exist_ok=True)
341    for d, j in jobs.items():
342        r = {"t": j["t"], "text_tokens": int(j["cond"].shape[0]), "image_tokens": j["H"] * j["W"]}
343        vel = {}
344        for mname in modes:
345            st = state[(d, mname)]
346            vel[mname] = head(Wt, make_mode(mname), st[2], st[3], st[1], j["H"], j["W"])
347            if a.trace:
348                trace_cmp(a.trace, d, mname, "head", {"velocity": (vel[mname].reshape(64, -1).T, "out.bin")})
349            if out:
350                np.save(out / f"{d.name}_{mname}.npy", vel[mname])
351        if "f32" in vel and "f16op" in vel:
352            r["f16op_vs_f32"] = compare(vel["f16op"].reshape(64, -1).T, vel["f32"].reshape(64, -1).T)
353        for spec in a.cmp:
354            name, pat = spec.split("=", 1)
355            p = Path(pat.replace("{dump}", str(d)).replace("{name}", d.name))
356            if not p.is_file():
357                continue
358            ref = np.fromfile(p, dtype="<f4").reshape(64, -1).T
359            for mname in modes:
360                r[f"{name}_vs_{mname}"] = compare(ref, vel[mname].reshape(64, -1).T)
361        res[d.name] = r
362        print(d.name, json.dumps({k: ({kk: round(vv, 6) if isinstance(vv, float) else vv for kk, vv in v.items()}
363                                      if isinstance(v, dict) else v) for k, v in r.items()}), flush=True)
364    keys = sorted({k for r in res.values() for k, v in r.items() if isinstance(v, dict)})
365    for k in keys:
366        rows = [r[k] for r in res.values() if k in r]
367        print(f"SUMMARY {k}: n {len(rows)} rel_l2 mean {np.mean([x['rel_l2'] for x in rows]):.6f} max "
368              f"{max(x['rel_l2'] for x in rows):.6f} cos min {min(x['cos'] for x in rows):.8f}")
369    if out:
370        (out / "dit_ref.json").write_text(json.dumps(res, indent=1))
371    if a.trace:
372        for dn in sorted({k[0] for k in TRACE}):
373            print(f"TRACE {dn}: stage | part | ours vs f32 | ours vs f16op | f16op vs f32")
374            for (n, stage, part), v in TRACE.items():
375                if n == dn:
376                    f = lambda key: f"{v[key]:.6f}" if key in v else "-"   # noqa: E731
377                    print(f"TRACE {dn} | {stage} | {part} | {f('f32')} | {f('f16op')} | {f('emu_vs_f32')}")
378        # alignment check: our block-i dump against the reference after blocks i-1, i, i+1 (f32 mode, image rows)
379        for dn in sorted({k[0] for k in STATES}):
380            tdir = Path(a.trace.replace("{name}", dn))
381            for i in (0, 1, 2, 5, 15, 30):
382                f = tdir / f"img_{i:02d}.bin"
383                if not f.is_file() or (dn, "f32", i) not in STATES:
384                    continue
385                L = next(st[3] for (dd, mm), st in state.items() if dd.name == dn and mm == "f32")
386                ours = np.fromfile(f, dtype="<f4").reshape(-1, STATES[(dn, "f32", i)].shape[1])
387                cells = []
388                for j in (i - 1, i, i + 1):
389                    if (dn, "f32", j) in STATES:
390                        cells.append(f"ref after block {j}: {compare(ours, STATES[(dn, 'f32', j)][L:])['rel_l2']:.5f}")
391                print(f"ALIGN {dn} ours img after block {i}: " + "; ".join(cells))
392        for (dn, mname), cp in sorted(CAPS.items()):
393            if mname != "f32" or not cp:
394                continue
395            tdir = Path(a.trace.replace("{name}", dn))
396            emu = CAPS.get((dn, "f16op"), {})
397            n = cp["att"].shape[0]
398            Hh, D = cp["q16"].shape[1], cp["q16"].shape[2]
399            def ours(name, shape, dt="<f4"):
400                f = tdir / name
401                return np.fromfile(f, dtype=dt).astype(np.float32).reshape(shape) if f.is_file() else None
402            q16 = ours("blk_q16.bin", (Hh, n, D), "<f2")
403            kvt = cp["k16"].shape[0]
404            got = {"qkv": ours("blk_qkv.bin", (n, -1)), "q16": None if q16 is None else q16.transpose(1, 0, 2),
405                   "k16": ours("blk_k16.bin", (Hh, kvt, D), "<f2"), "v16": ours("blk_v16.bin", (Hh, kvt, D), "<f2"),
406                   "att": ours("blk_att.bin", (n, -1)), "x_mid": ours("blk_x_mid.bin", (n, -1)), "ln2": ours("blk_ln2.bin", (n, -1)),
407                   "act": ours("blk_act.bin", (n, -1))}
408            for key in ("k16", "v16"):
409                if got[key] is not None:
410                    got[key] = got[key].transpose(1, 0, 2)
411            print(f"BLOCK {a.trace_block} {dn} | stage | ours vs f32 | ours vs f16op | f16op vs f32")
412            for key in ("qkv", "q16", "k16", "v16", "att", "x_mid", "ln2", "act"):
413                g = got[key]
414                if g is None:
415                    continue
416                r = cp[key].reshape(g.shape[0], -1)
417                gg = g.reshape(g.shape[0], -1)
418                e = emu[key].reshape(g.shape[0], -1) if key in emu else None
419                f = lambda x, y: "%.6f" % compare(x, y)["rel_l2"]   # noqa: E731
420                ge = f(gg, e) if e is not None else "-"
421                er = f(e, r) if e is not None else "-"
422                print(f"BLOCK {a.trace_block} {dn} | {key} | {f(gg, r)} | {ge} | {er}")
423        for (dn, mname), mx in MAXIMA.items():
424            if mname == "f32":
425                print(f"MAXIMA {dn} f32 " + json.dumps({k: round(x, 4) for k, x in mx.items()}))
426        if out:
427            (out / "trace.json").write_text(json.dumps({"trace": {" | ".join(k): v for k, v in TRACE.items()},
428                                                        "maxima": {" | ".join(k): v for k, v in MAXIMA.items()}}))
429    return 0
430
431
432if __name__ == "__main__":
433    sys.exit(main())