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
6.7 KiB143 linesraw
1"""tools/image/gate/dit_replay.py - TEST-ONLY (OWN-5B trace): replay one DiT block of dit_ref.py from OUR stream.
2
3Our test build (STRATA_DIT_TRACE_DIR, STRATA_DIT_TRACE_BLOCK=B) dumps the stream after every block (txt_NN.bin,
4img_NN.bin) and the inside of block B (blk_*.bin).  This tool:
5  1. runs dit_ref's block B in f32 and in f16op starting from OUR stream after block B-1, and compares each stage with
6     our dump of the same stage: same input, so what is left is the difference in the block's own arithmetic;
7  2. runs the reference up to block B-1 (f32 and f16op), then block B in f32 from three inputs: the f32 state, the
8     f16op state and our state; the attention output's distance from the f32-from-f32 one against the input's
9     distance tells how much block B amplifies a given input difference, per input;
10  3. the same with random input perturbations of the size of ours (three trials), to see whether block B of this
11     prompt amplifies any small difference or only ours;
12  4. a K / V layout check (rows of our blk_k16 / blk_v16 against the reference's text and image rows).
13
14    python -I -B dit_replay.py <dit.gguf> --dump D --trace T --block B
15"""
16from __future__ import annotations
17
18import argparse
19import sys
20from pathlib import Path
21
22import numpy as np
23
24_HERE = Path(__file__).resolve().parent
25if str(_HERE) not in sys.path:
26    sys.path.insert(0, str(_HERE))
27from dit_ref import DitWeights, Mode, block, layer_norm, layout_positions, load_dump, prelude, rope_table  # noqa: E402
28from te_ref import compare  # noqa: E402
29
30F32 = np.float32
31KEYS = ("qkv", "q16", "att", "x_mid", "ln2", "act")
32
33
34def rel(a, b) -> float:
35    return compare(np.asarray(a, F32).reshape(a.shape[0], -1), np.asarray(b, F32).reshape(b.shape[0], -1))["rel_l2"]
36
37
38def ours_block(t: Path, n: int, H: int, D: int) -> dict:
39    def rd(name, shape, dt="<f4"):
40        f = t / name
41        return np.fromfile(f, dtype=dt).astype(F32).reshape(shape) if f.is_file() else None
42    q = rd("blk_q16.bin", (H, n, D), "<f2")
43    return {"qkv": rd("blk_qkv.bin", (n, -1)), "q16": None if q is None else q.transpose(1, 0, 2),
44            "att": rd("blk_att.bin", (n, -1)), "x_mid": rd("blk_x_mid.bin", (n, -1)), "ln2": rd("blk_ln2.bin", (n, -1)),
45            "act": rd("blk_act.bin", (n, -1))}
46
47
48def main(argv=None) -> int:
49    ap = argparse.ArgumentParser()
50    ap.add_argument("gguf")
51    ap.add_argument("--dump", required=True)
52    ap.add_argument("--trace", required=True)
53    ap.add_argument("--block", type=int, required=True)
54    ap.add_argument("--trials", type=int, default=3)
55    a = ap.parse_args(argv)
56    B = a.block
57    d, t = Path(a.dump), Path(a.trace)
58    name = d.name
59    Wt = DitWeights(Path(a.gguf))
60    xv, xs = load_dump(d, "dit_x_0")
61    tv, _ = load_dump(d, "dit_t_0")
62    cv, cs = load_dump(d, "cond")
63    Ww, Hh, C = xs[0], xs[1], xs[2]
64    x, tt, cond = xv.reshape(C, Hh, Ww), float(tv[0]), cv.reshape(cs[1], cs[0])
65    L = cond.shape[0]
66    c, s = rope_table(layout_positions(L, Hh, Ww))
67    ours_prev = np.concatenate([np.fromfile(t / f"txt_{B - 1:02d}.bin", dtype="<f4").reshape(L, -1),
68                                np.fromfile(t / f"img_{B - 1:02d}.bin", dtype="<f4").reshape(Hh * Ww, -1)], 0)
69    n = Hh * Ww
70    H, D = ours_prev.shape[1] // 128, 128
71    got = ours_block(t, n, H, D)
72    st = {}
73    for mname in ("f32", "f16op"):
74        m = Mode(mname == "f16op")
75        mods, scale, xj = prelude(Wt, m, tt, cond, x)
76        rows = np.array([1] * L + [0] * (xj.shape[0] - L))
77        for i in range(B):
78            xj = block(Wt, m, i, xj, rows, mods, L, c, s)
79        st[mname] = (m, mods, rows, xj)
80        print(f"{name}: {mname} state after block {B - 1} done", flush=True)
81    for nm, (m, mods, rows, xj) in st.items():
82        print(f"INPUT {name} | {nm} state vs ours after block {B - 1} | img {rel(xj[L:], ours_prev[L:]):.6f} | "
83              f"img LN {rel(layer_norm(xj[L:]), layer_norm(ours_prev[L:])):.6f} | txt {rel(xj[:L], ours_prev[:L]):.6f}")
84    # 1. same input (ours), the block's arithmetic only
85    caps = {}
86    for nm, (m, mods, rows, _) in st.items():
87        cap = {}
88        block(Wt, m, B, ours_prev.copy(), rows, mods, L, c, s, None, None, cap)
89        caps[nm] = cap
90    print(f"REPLAY {name} block {B} from OUR input | stage | ours vs f32 | ours vs f16op | f16op vs f32")
91    for k in KEYS:
92        g = got[k]
93        if g is None:
94            continue
95        print(f"REPLAY {name} | {k} | {rel(g, caps['f32'][k]):.6f} | {rel(g, caps['f16op'][k]):.6f} | "
96              f"{rel(caps['f16op'][k], caps['f32'][k]):.6f}")
97    # 2. block B in f32 from three inputs
98    m32, mods32, rows32, x32 = st["f32"]
99
100    def att_from(xin):
101        cap = {}
102        block(Wt, m32, B, xin.copy(), rows32, mods32, L, c, s, None, None, cap)
103        return cap
104
105    base = att_from(x32)
106    print(f"AMPLIFY {name} block {B} (f32 arithmetic) | input | input img LN dist | att dist | act dist | att / input")
107    for nm, xin in (("f16op state", st["f16op"][3]), ("our state", ours_prev)):
108        cp = att_from(xin)
109        di = rel(layer_norm(xin[L:]), layer_norm(x32[L:]))
110        da, dact = rel(cp["att"], base["att"]), rel(cp["act"], base["act"])
111        print(f"AMPLIFY {name} | {nm} | {di:.6f} | {da:.6f} | {dact:.6f} | {da / max(di, 1e-30):.2f}")
112    # 3. random perturbations of our input's size (image rows only, per-row relative)
113    di_ours = rel(ours_prev[L:], x32[L:])
114    rng = np.random.default_rng(1)
115    for k in range(a.trials):
116        e = rng.standard_normal(x32[L:].shape).astype(F32)
117        e *= (np.linalg.norm(x32[L:], axis=1, keepdims=True) / np.linalg.norm(e, axis=1, keepdims=True)) * F32(di_ours)
118        xin = x32.copy()
119        xin[L:] += e
120        cp = att_from(xin)
121        di = rel(layer_norm(xin[L:]), layer_norm(x32[L:]))
122        da, dact = rel(cp["att"], base["att"]), rel(cp["act"], base["act"])
123        print(f"AMPLIFY {name} | random {k} | {di:.6f} | {da:.6f} | {dact:.6f} | {da / max(di, 1e-30):.2f}")
124    # 4. K / V layout of our dump
125    for key, f in (("k16", "blk_k16.bin"), ("v16", "blk_v16.bin")):
126        p = t / f
127        if not p.is_file():
128            continue
129        arr = np.fromfile(p, dtype="<f2").astype(F32)
130        kvt = arr.size // (H * D)
131        o = arr.reshape(H, kvt, D).transpose(1, 0, 2)
132        r = caps["f16op"][key]                                   # [L + n, H, D]
133        cells = [f"kvt {kvt} (L {L} + n {n} = {L + n})"]
134        if kvt >= L + n:
135            cells.append(f"[text;image] {rel(o[:L + n], r):.6f}")
136            cells.append(f"text rows {rel(o[:L], r[:L]):.6f} image rows {rel(o[L:L + n], r[L:]):.6f}")
137            cells.append(f"[image;text] {rel(np.concatenate([o[n:n + L], o[:n]], 0), r):.6f}")
138        print(f"LAYOUT {name} | {key} | " + " | ".join(cells))
139    return 0
140
141
142if __name__ == "__main__":
143    sys.exit(main())