okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
28ce98bf1
main
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 ): 17global fails 18if not c : 19fails += 1 20"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 ): 27s = tqenc .make_signs (n ,5 ) 28check (set (np .unique (s ))<= {- 1.0 ,1.0 },"signs +-1" ) 29check (np .array_equal (tqenc .unpack_signs (tqenc .pack_signs (s ),n ),s ),"sign pack round trip" ) 30W = rng .standard_normal ((8 ,n )).astype (np .float32 ) 31x = rng .standard_normal (n ).astype (np .float32 ) 32Wr = tqenc .rotate (W ,s ) 33check (np .abs (tqenc .unrotate (Wr ,s )- W ).max ()< 1e-5 ,"unrotate(rotate(W)) == W" ) 34Ux = tqenc .rotate (x [None , :],s )[0 ] 35check (np .abs (Wr @Ux - W @x ).max ()< 1e-3 ,"Wrot (U x) == W x before quantization" ) 36for t in (tqenc .TQK4X ,tqenc .TQK5X ,tqenc .TQK4T ,tqenc .TQK5T ,tqenc .TQK6 ,tqenc .TQK7 ,tqenc .TQ2_T ): 37packed ,err ,tot ,st = tqenc .encode (Wr ,t ,iters = 0 ) 38check (packed .shape == (8 * n // 128 ,tqenc .block_bytes (t )),"packed shape" ) 39Q = tqenc .decode (packed ,t ).reshape (8 ,n ) 40y1 = Q @Ux 41y2 = tqenc .unrotate (Q ,s ) @x 42check (np .abs (y1 - y2 ).max ()< 1e-3 * max (1.0 ,np .abs (y1 ).max ()),"Q(Ux) == unrotate(Q) x type %d" % t ) 43check (abs (tot - np .sum ((Wr .astype (np .float64 )- Q )** 2 ))< 1e-4 * tot ,"encoder error == decoded error" ) 44with tempfile .TemporaryDirectory ()as d : 45p = os .path .join (d ,"m.tqx" ) 46tqenc .write_tqx (p ,t ,8 ,n ,packed ,s ) 47t2 ,r2 ,c2 ,pk2 ,s2 = tqenc .read_tqx (p ) 48check (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" ) 51"python checks:" ,"OK" if not fails else "%d FAILED" % fails ) 52sys .exit (1 if fails else 0 )