okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
28ce98bf1
main
1"""tqenc.py - Python side of the trellis encoder (tools/trellis/tqenc.cpp, built to libtqenc.so by 2`sh tools/trellis/build.sh lib`): encode / decode blocks of TQ2_T, TQK6, TQK7 and the experimental TQK5X / TQK4X, the 3input-only block Hadamard of the DeepSeek plan, and error metrics. 4 5Rows of a tensor are blocks of 128 consecutive weights along the INPUT dimension (the GGUF fastest axis), exactly as the 6decoders read them. A tensor of shape [rows, n] (n a multiple of 128) is encoded row by row; the output has 7rows * n/128 * block_bytes bytes. 8""" 9from __future__import annotations 10 11import ctypes 12import os 13import pathlib 14 15import numpy as np 16 17TQ2_T ,TQK6 ,TQK7 ,TQK5X ,TQK4X ,TQK5T ,TQK4T = 144 ,145 ,146 ,224 ,225 ,226 ,227 18# TQK5X / TQK4X: experimental version 2, the computed (LUT-free) codebook (src/kernels/cpu/tq_computed.hpp); 19# TQK5T / TQK4T: version 1, the fork's point table (what the first pilots and the Gyro-S checks used for K5 / K4) 20TYPE_NAMES = {TQ2_T :"TQ2_T" ,TQK6 :"TQK6" ,TQK7 :"TQK7" ,TQK5X :"TQK5X" ,TQK4X :"TQK4X" ,TQK5T :"TQK5T" ,TQK4T :"TQK4T" } 21TYPE_BY_NAME = {v :k for k ,v in TYPE_NAMES .items ()} 22KBITS = {TQ2_T :8 ,TQK6 :6 ,TQK7 :7 ,TQK5X :5 ,TQK4X :4 ,TQK5T :5 ,TQK4T :4 } 23COMPUTED = (TQK5X ,TQK4X ) 24BLOCK = 128 25 26 27def block_bytes (t :int )-> int : 28return 2 + 4 * KBITS [t ] 29 30 31def bpw (t :int )-> float : 32return block_bytes (t )* 8 / BLOCK 33 34 35_lib = None 36 37 38def lib ()-> ctypes .CDLL : 39global _lib 40if _lib is None : 41cands = [os .environ .get ("TQENC_LIB" ,"" ), 42str (pathlib .Path (__file__ ).resolve ().parent .parent / "build-tqenc" / "libtqenc.so" ), 43"libtqenc.so" ] 44last = None 45for c in cands : 46if not c : 47continue 48try : 49_lib = ctypes .CDLL (c ) 50break 51except OSError as e : 52last = e 53if _lib is None : 54raise RuntimeError ("libtqenc.so not found (sh tools/trellis/build.sh lib): %s" % last ) 55_lib .tqe_encode .restype = ctypes .c_double 56_lib .tqe_encode .argtypes = [ctypes .c_int ,ctypes .c_void_p ,ctypes .c_void_p ,ctypes .c_int64 ,ctypes .c_void_p , 57ctypes .c_int ,ctypes .c_int ,ctypes .c_int ,ctypes .c_int ,ctypes .c_int , 58ctypes .c_void_p ,ctypes .c_void_p ] 59_lib .tqe_decode .restype = None 60_lib .tqe_decode .argtypes = [ctypes .c_int ,ctypes .c_void_p ,ctypes .c_int64 ,ctypes .c_void_p ] 61return _lib 62 63 64_hip = None 65 66 67class _gpu_lock : 68"""TQENC_GPU_LOCK=<card number>: take the box locks (shared /data/gpu.lock, exclusive ~/locks/gpu<N>.lock) around every GPU 69call and release them in between, so a long job that is mostly host work does not keep the card from other users. 70TQENC_GPU_WAIT=<seconds> (default: wait for ever): give up after that long; `ok` is then False and encode() uses the CPU.""" 71 72def __init__ (self ): 73self .fds = [] 74self .ok = True 75 76def __enter__ (self ): 77card = os .environ .get ("TQENC_GPU_LOCK" ) 78if card is None : 79return self 80import fcntl 81import time 82wait = float (os .environ .get ("TQENC_GPU_WAIT" ,"1e9" )) 83t0 = time .time () 84while os .path .exists (os .path .expanduser ("~/locks/EXCL_WAIT" )):# a writer is waiting for the box 85if time .time ()- t0 > wait : 86self .ok = False 87return self 88time .sleep (2 ) 89for path ,mode in (("/data/gpu.lock" ,fcntl .LOCK_SH ), (os .path .expanduser ("~/locks/gpu%s.lock" % card ),fcntl .LOCK_EX )): 90fd = os .open (path ,os .O_RDWR | os .O_CREAT ) 91while True : 92try : 93fcntl .flock (fd ,mode | fcntl .LOCK_NB ) 94break 95except BlockingIOError : 96if time .time ()- t0 > wait : 97os .close (fd ) 98self .ok = False 99for f in reversed (self .fds ): 100os .close (f ) 101self .fds = [] 102return self 103time .sleep (0.2 ) 104self .fds .append (fd ) 105return self 106 107def __exit__ (self ,* a ): 108for fd in reversed (self .fds ): 109os .close (fd ) 110return False 111 112 113def hip_lib ()-> ctypes .CDLL : 114"""libtqenc_hip.so (sh tools/trellis/build.sh hip; run under the box GPU locks, HIP_VISIBLE_DEVICES picks the card).""" 115global _hip 116if _hip is None : 117cands = [os .environ .get ("TQENC_HIP_LIB" ,"" ), 118str (pathlib .Path (__file__ ).resolve ().parent .parent / "build-tqenc" / "libtqenc_hip.so" )] 119last = None 120for c in cands : 121if not c : 122continue 123try : 124_hip = ctypes .CDLL (c ) 125break 126except OSError as e : 127last = e 128if _hip is None : 129raise RuntimeError ("libtqenc_hip.so not found: %s" % last ) 130_hip .tqh_encode .restype = ctypes .c_double 131_hip .tqh_encode .argtypes = [ctypes .c_int ,ctypes .c_void_p ,ctypes .c_void_p ,ctypes .c_int64 ,ctypes .c_void_p , 132ctypes .c_int ,ctypes .c_int ,ctypes .c_int ,ctypes .c_int ,ctypes .c_void_p , 133ctypes .c_void_p ,ctypes .c_void_p ,ctypes .c_int ] 134return _hip 135 136 137def encode (w :np .ndarray ,t :int ,h :np .ndarray | None = None ,iters :int = 1 ,ncand :int = 1 ,exact :int = 0 , 138scale_tries :int = 1 ,threads :int = 0 ,gpu :bool = False ): 139"""w: float32 array whose last axis is a multiple of 128. Returns (packed uint8 [nblocks, block_bytes], 140per-block error float64 [nblocks], total error, stats dict). Error = sum h (w - decoded)^2 (h = 1 if None).""" 141w = np .ascontiguousarray (w ,dtype = np .float32 ) 142if w .shape [- 1 ]% BLOCK : 143raise ValueError ("last axis %d is not a multiple of 128" % w .shape [- 1 ]) 144nb = w .size // BLOCK 145out = np .zeros ((nb ,block_bytes (t )),dtype = np .uint8 ) 146err = np .zeros (nb ,dtype = np .float64 ) 147stats = np .zeros (2 ,dtype = np .int64 ) 148hp = None 149if h is not None : 150h = np .ascontiguousarray (h ,dtype = np .float32 ) 151if h .shape != w .shape : 152raise ValueError ("importance weights must have the shape of w" ) 153hp = h .ctypes .data 154if gpu : 155if exact or t == TQ2_T : 156raise ValueError ("the GPU encoder has no exact search and no TQ2_T" ) 157with _gpu_lock ()as gl : 158if gl .ok : 159tot = hip_lib ().tqh_encode (t ,w .ctypes .data ,hp ,nb ,out .ctypes .data ,iters ,ncand ,scale_tries ,0 , 160err .ctypes .data ,stats .ctypes .data ,None ,0 ) 161return out ,err ,tot , {"nonfinite_blocks" :int (stats [0 ]),"zero_blocks" :int (stats [1 ])} 162threads = int (os .environ .get ("TQENC_CPU_THREADS" ,threads or 24 ))# the card stayed busy: the CPU encoder, same blocks 163tot = lib ().tqe_encode (t ,w .ctypes .data ,hp ,nb ,out .ctypes .data ,iters ,ncand ,exact ,scale_tries ,threads , 164err .ctypes .data ,stats .ctypes .data ) 165return out ,err ,tot , {"nonfinite_blocks" :int (stats [0 ]),"zero_blocks" :int (stats [1 ])} 166 167 168def decode (packed :np .ndarray ,t :int )-> np .ndarray : 169"""packed: uint8 array of whole blocks. Returns float32 [nblocks * 128] (d * codebook).""" 170packed = np .ascontiguousarray (packed ,dtype = np .uint8 ) 171bb = block_bytes (t ) 172if packed .size % bb : 173raise ValueError ("%d bytes is not a whole number of %s blocks" % (packed .size ,TYPE_NAMES [t ])) 174nb = packed .size // bb 175out = np .zeros (nb * BLOCK ,dtype = np .float32 ) 176lib ().tqe_decode (t ,packed .ctypes .data ,nb ,out .ctypes .data ) 177return out 178 179 180# ---------------------------------------------------------------------------------------------------- Hadamard 181 182def hadamard_matrix (n :int = BLOCK )-> np .ndarray : 183"""The normalized Sylvester-Walsh-Hadamard matrix (entry (-1)^popcount(r & c) / sqrt(n)); symmetric, orthonormal.""" 184h = np .array ([[1.0 ]]) 185while h .shape [0 ]< n : 186h = np .block ([[h ,h ], [h ,- h ]]) 187return (h / np .sqrt (n )).astype (np .float32 ) 188 189 190def make_signs (width :int ,seed :int )-> np .ndarray : 191"""A reproducible +1/-1 vector (the plan's D). The vector itself, not the seed, is what a file must store.""" 192r = np .random .default_rng (seed ) 193return (r .integers (0 ,2 ,size = width )* 2 - 1 ).astype (np .float32 ) 194 195 196def pack_signs (signs :np .ndarray )-> bytes : 197return np .packbits ((signs > 0 ).astype (np .uint8 ),bitorder = "little" ).tobytes () 198 199 200def unpack_signs (b :bytes ,width :int )-> np .ndarray : 201bits = np .unpackbits (np .frombuffer (b ,dtype = np .uint8 ),bitorder = "little" )[:width ] 202return bits .astype (np .float32 )* 2 - 1 203 204 205def rotate (w :np .ndarray ,signs :np .ndarray | None )-> np .ndarray : 206"""The input transform U = H D on the last axis, per 128-block: Wrot = W U^T, i.e. each row w -> H (signs * w). 207The same function applied to an activation x gives U x.""" 208w = np .asarray (w ,dtype = np .float32 ) 209if signs is not None : 210w = w * signs 211shp = w .shape 212return (w .reshape (- 1 ,BLOCK ) @hadamard_matrix ()).reshape (shp )# H is symmetric 213 214 215def unrotate (w :np .ndarray ,signs :np .ndarray | None )-> np .ndarray : 216"""Inverse of rotate (H is its own inverse: orthonormal and symmetric; then the signs).""" 217shp = w .shape 218x = (np .asarray (w ,dtype = np .float32 ).reshape (- 1 ,BLOCK ) @hadamard_matrix ()).reshape (shp ) 219return x * signs if signs is not None else x 220 221 222# ---------------------------------------------------------------------------------------------------- metrics 223 224def sqnr_db (ref :np .ndarray ,approx :np .ndarray )-> float : 225ref = np .asarray (ref ,dtype = np .float64 ).ravel () 226e = np .sum ((ref - np .asarray (approx ,dtype = np .float64 ).ravel ())** 2 ) 227return float ("inf" )if e == 0 else float (10 * np .log10 (np .sum (ref ** 2 )/ e )) 228 229 230def rel_mse (ref :np .ndarray ,approx :np .ndarray )-> float : 231ref = np .asarray (ref ,dtype = np .float64 ).ravel () 232return float (np .sum ((ref - np .asarray (approx ,dtype = np .float64 ).ravel ())** 2 )/ max (np .sum (ref ** 2 ),1e-300 )) 233 234 235# ---------------------------------------------------------------------------------------------------- .tqx container 236# A small versioned file for ONE encoded matrix (research artifacts; not a GGUF). Little endian: 237# "TQXP" | u32 version (1) | u32 type id | u32 rows | u32 cols | u32 flags (bit 0: input Hadamard, 128-blocks) 238# | u32 n_sign_bytes | sign bits (1 = +1, LSB first, one per input column) | u32 hadamard block (128) | packed blocks 239# An unknown version or type is refused before any data is read. 240TQX_MAGIC = b"TQXP" 241TQX_VERSION = 2 # 2: types 224 / 225 are the computed codebook; a version 1 file means the point table (226 / 227) 242 243 244def write_tqx (path ,t :int ,rows :int ,cols :int ,packed :np .ndarray ,signs :np .ndarray | None )-> None : 245import struct 246sb = pack_signs (signs )if signs is not None else b"" 247with open (path ,"wb" )as f : 248f .write (TQX_MAGIC + struct .pack ("<IIIIII" ,TQX_VERSION ,t ,rows ,cols ,1 if signs is not None else 0 ,len (sb ))) 249f .write (sb ) 250f .write (struct .pack ("<I" ,BLOCK )) 251f .write (np .ascontiguousarray (packed ,dtype = np .uint8 ).tobytes ()) 252 253 254def read_tqx (path ): 255import struct 256data = open (path ,"rb" ).read () 257if data [:4 ]!= TQX_MAGIC : 258raise ValueError ("not a TQXP file" ) 259ver ,t ,rows ,cols ,flags ,nsb = struct .unpack_from ("<IIIIII" ,data ,4 ) 260if ver == 1 and t in (TQK5X ,TQK4X ): 261t += 2 # a version 1 file: the point table 262elif ver != TQX_VERSION : 263raise ValueError ("unsupported TQXP version %d (this reader handles %d, and 1 for the point-table K5 / K4)" % (ver ,TQX_VERSION )) 264if t not in KBITS : 265raise ValueError ("unknown trellis type %d" % t ) 266at = 4 + 24 267signs = unpack_signs (data [at :at + nsb ],cols )if flags & 1 else None 268at += nsb 269 (blk ,)= struct .unpack_from ("<I" ,data ,at ) 270at += 4 271if blk != BLOCK : 272raise ValueError ("unsupported Hadamard block %d" % blk ) 273nb = rows * (cols // BLOCK ) 274packed = np .frombuffer (data ,dtype = np .uint8 ,count = nb * block_bytes (t ),offset = at ).reshape (nb ,block_bytes (t )) 275return t ,rows ,cols ,packed ,signs