okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
28ce98bf1
main
1"""blockldl.py - Hessian-aware trellis encoding by block feedback (the block form of GPTQ / LDLQ, as QTIP does it). 2 3Weights W [m, n] in the rotated basis, H = E[x x^T] [n, n] of the rotated layer input. Columns are cut into 128-blocks (the 4trellis blocks). Block b is encoded on its own (m blocks of 128, plain-MSE trellis search), its error E_b = W_b - Q_b is 5pushed onto the not yet coded columns, exactly as the OBS update does for a whole block: 6 7W[:, c1:] -= E_b R_bb^{-1} R[c0:c1, c1:] R upper, H^-1 = R^T R 8 9so the later blocks absorb what the earlier ones could not represent, in the directions that matter for ||(W - Q) X||. 10The result is a normal TQK6 / TQK7 / TQK5X / TQK4X tensor; only the encoder changed. 11""" 12from __future__import annotations 13 14import numpy as np 15 16import tqenc 17 18try : 19from scipy .linalg import solve_triangular 20except Exception :# numpy only: a small back substitution 21solve_triangular = None 22 23 24def _solve_upper (A :np .ndarray ,B :np .ndarray )-> np .ndarray : 25if solve_triangular is not None : 26return solve_triangular (A ,B ,lower = False ) 27return np .linalg .solve (A ,B ) 28 29 30def hessian_factor (H :np .ndarray ,damp :float = 0.01 )-> np .ndarray : 31"""R (upper) with (H + damp * mean(diag H) I)^-1 = R^T R.""" 32H = np .asarray (H ,dtype = np .float64 ).copy () 33d = damp * float (np .mean (np .diag (H ))) 34H [np .diag_indices_from (H )]+= d 35Hinv = np .linalg .inv (H ) 36Hinv = (Hinv + Hinv .T )* 0.5 37L = np .linalg .cholesky (Hinv ) 38return L .T 39 40 41def feedback_matrices (R :np .ndarray ,g :int = 128 ): 42"""For every block b the matrix R_bb^{-1} R[b, b+1:] ([g, n - (b+1) g]); the last block has none.""" 43n = R .shape [0 ] 44out = [] 45for c0 in range (0 ,n ,g ): 46c1 = c0 + g 47out .append (_solve_upper (R [c0 :c1 ,c0 :c1 ],R [c0 :c1 ,c1 :]).astype (np .float32 )if c1 < n else None ) 48return out 49 50 51def encode_ldl (W :np .ndarray ,t :int ,fb ,gpu :bool = False ,iters :int = 1 ,ncand :int = 1 ,threads :int = 0 ): 52"""W [m, n] float32 (n % 128 == 0), fb from feedback_matrices. Returns (packed [m, n/128, block_bytes], decoded [m, n]).""" 53m ,n = W .shape 54B = n // 128 55bb = tqenc .block_bytes (t ) 56Wc = np .ascontiguousarray (W ,dtype = np .float32 ).copy () 57packed = np .empty ((m ,B ,bb ),dtype = np .uint8 ) 58dec = np .empty ((m ,n ),dtype = np .float32 ) 59kw = dict (iters = iters ,ncand = ncand ) 60if gpu : 61kw ["gpu" ]= True 62else : 63kw ["threads" ]= threads 64for b in range (B ): 65c0 ,c1 = b * 128 , (b + 1 )* 128 66blk = np .ascontiguousarray (Wc [:,c0 :c1 ]) 67pk ,_ ,_ ,_ = tqenc .encode (blk ,t ,** kw ) 68q = tqenc .decode (pk ,t ).reshape (m ,128 ) 69packed [:,b ]= pk 70dec [:,c0 :c1 ]= q 71if fb [b ]is not None : 72Wc [:,c1 :]-= (blk - q ) @fb [b ] 73return packed ,dec