okami.mom/strata

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

Niko1221Merge f-dsv41-rel (0be62ccad) into v0.2.3.1: DeepSeek V4.1-Flash on top of the released 0.2.3 line28ce98bf1

main
2.4 KiB52 linesraw
1"""Python-level checks of tools/tqenc.py (run on the box with libtqenc.so built): Hadamard orthonormality and the
2Q(Ux) == Q_orig x identity through the encoder, signs and .tqx round trips, K5/K4 sizes."""
3import os
4import sys
5import tempfile
6import pathlib
7
8import numpy as np
9
10sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent))
11import tqenc  # noqa: E402
12
13fails = 0
14
15
16def check(c, msg):
17    global fails
18    if not c:
19        fails += 1
20        print("FAIL", msg)
21
22
23H = tqenc.hadamard_matrix()
24check(np.abs(H @ H.T - np.eye(128)).max() < 1e-6 and np.abs(H - H.T).max() == 0, "H128 orthonormal and symmetric")
25rng = np.random.default_rng(3)
26for n in (2304, 5120):
27    s = tqenc.make_signs(n, 5)
28    check(set(np.unique(s)) <= {-1.0, 1.0}, "signs +-1")
29    check(np.array_equal(tqenc.unpack_signs(tqenc.pack_signs(s), n), s), "sign pack round trip")
30    W = rng.standard_normal((8, n)).astype(np.float32)
31    x = rng.standard_normal(n).astype(np.float32)
32    Wr = tqenc.rotate(W, s)
33    check(np.abs(tqenc.unrotate(Wr, s) - W).max() < 1e-5, "unrotate(rotate(W)) == W")
34    Ux = tqenc.rotate(x[None, :], s)[0]
35    check(np.abs(Wr @ Ux - W @ x).max() < 1e-3, "Wrot (U x) == W x before quantization")
36    for t in (tqenc.TQK4X, tqenc.TQK5X, tqenc.TQK4T, tqenc.TQK5T, tqenc.TQK6, tqenc.TQK7, tqenc.TQ2_T):
37        packed, err, tot, st = tqenc.encode(Wr, t, iters=0)
38        check(packed.shape == (8 * n // 128, tqenc.block_bytes(t)), "packed shape")
39        Q = tqenc.decode(packed, t).reshape(8, n)
40        y1 = Q @ Ux
41        y2 = tqenc.unrotate(Q, s) @ x
42        check(np.abs(y1 - y2).max() < 1e-3 * max(1.0, np.abs(y1).max()), "Q(Ux) == unrotate(Q) x  type %d" % t)
43        check(abs(tot - np.sum((Wr.astype(np.float64) - Q) ** 2)) < 1e-4 * tot, "encoder error == decoded error")
44        with tempfile.TemporaryDirectory() as d:
45            p = os.path.join(d, "m.tqx")
46            tqenc.write_tqx(p, t, 8, n, packed, s)
47            t2, r2, c2, pk2, s2 = tqenc.read_tqx(p)
48            check(t2 == t and r2 == 8 and c2 == n and np.array_equal(pk2, packed) and np.array_equal(s2, s), "tqx round trip")
49check(tqenc.block_bytes(tqenc.TQK5X) == 22 and tqenc.block_bytes(tqenc.TQK4X) == 18, "K5 22 bytes, K4 18 bytes")
50check(abs(tqenc.bpw(tqenc.TQK5X) - 1.375) < 1e-9 and abs(tqenc.bpw(tqenc.TQK4X) - 1.125) < 1e-9, "bpw")
51print("python checks:", "OK" if not fails else "%d FAILED" % fails)
52sys.exit(1 if fails else 0)