okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
28ce98bf1
main
1"""test_blockldl.py - block feedback against plain encoding on a synthetic anisotropic H (an incoherent random basis with a 2spread spectrum) and on real expert weights: the proxy loss tr(E H E^T) must drop, the plain loss rises a little. 3python3 tools/trellis/test_blockldl.py [--orig DIR --layer 4] 4""" 5import argparse 6import pathlib 7import sys 8 9import numpy as np 10 11HERE = pathlib .Path (__file__ ).resolve ().parent 12sys .path .insert (0 ,str (HERE .parent )) 13sys .path .insert (0 ,str (HERE )) 14import blockldl # noqa: E402 15import tqenc # noqa: E402 16 17ap = argparse .ArgumentParser () 18ap .add_argument ("--n" ,type = int ,default = 1024 ) 19ap .add_argument ("--rows" ,type = int ,default = 512 ) 20ap .add_argument ("--spread" ,type = float ,default = 100.0 ,help = "ratio of the largest to the smallest eigenvalue" ) 21ap .add_argument ("--type" ,default = "TQK6" ) 22a = ap .parse_args () 23t = tqenc .TYPE_BY_NAME [a .type ] 24rng = np .random .default_rng (1 ) 25n = a .n 26Q ,_ = np .linalg .qr (rng .standard_normal ((n ,n ))) 27lam = np .logspace (0 ,- np .log10 (a .spread ),n ) 28H = (Q * lam ) @Q .T 29W = (rng .standard_normal ((a .rows ,n ))* 0.02 ).astype (np .float32 ) 30R = blockldl .hessian_factor (H ,0.01 ) 31fb = blockldl .feedback_matrices (R ) 32pk ,_ ,_ ,_ = tqenc .encode (W ,t ,iters = 1 ,threads = 8 ) 33plain = tqenc .decode (pk ,t ).reshape (W .shape ) 34_ ,ldl = blockldl .encode_ldl (W ,t ,fb ,threads = 8 ) 35 36 37def proxy (Wq ): 38E = (W - Wq ).astype (np .float64 ) 39return np .trace (E @H @E .T )/ np .trace (W .astype (np .float64 ) @H @W .T .astype (np .float64 )) 40 41 42for name ,Wq in (("plain" ,plain ), ("block LDL" ,ldl )): 43E = W - Wq 44"%-10s unweighted %.2f dB H-weighted %.2f dB" % (name ,10 * np .log10 (np .sum (W .astype (np .float64 )** 2 )/ np .sum (E .astype (np .float64 )** 2 )),- 10 * np .log10 (proxy (Wq ))))