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
11.9 KiB275 linesraw
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:
28    return 2 + 4 * KBITS[t]
29
30
31def bpw(t: int) -> float:
32    return block_bytes(t) * 8 / BLOCK
33
34
35_lib = None
36
37
38def lib() -> ctypes.CDLL:
39    global _lib
40    if _lib is None:
41        cands = [os.environ.get("TQENC_LIB", ""),
42                 str(pathlib.Path(__file__).resolve().parent.parent / "build-tqenc" / "libtqenc.so"),
43                 "libtqenc.so"]
44        last = None
45        for c in cands:
46            if not c:
47                continue
48            try:
49                _lib = ctypes.CDLL(c)
50                break
51            except OSError as e:
52                last = e
53        if _lib is None:
54            raise 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,
57                                    ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int,
58                                    ctypes.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]
61    return _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
69    call and release them in between, so a long job that is mostly host work does not keep the card from other users.
70    TQENC_GPU_WAIT=<seconds> (default: wait for ever): give up after that long; `ok` is then False and encode() uses the CPU."""
71
72    def __init__(self):
73        self.fds = []
74        self.ok = True
75
76    def __enter__(self):
77        card = os.environ.get("TQENC_GPU_LOCK")
78        if card is None:
79            return self
80        import fcntl
81        import time
82        wait = float(os.environ.get("TQENC_GPU_WAIT", "1e9"))
83        t0 = time.time()
84        while os.path.exists(os.path.expanduser("~/locks/EXCL_WAIT")):   # a writer is waiting for the box
85            if time.time() - t0 > wait:
86                self.ok = False
87                return self
88            time.sleep(2)
89        for path, mode in (("/data/gpu.lock", fcntl.LOCK_SH), (os.path.expanduser("~/locks/gpu%s.lock" % card), fcntl.LOCK_EX)):
90            fd = os.open(path, os.O_RDWR | os.O_CREAT)
91            while True:
92                try:
93                    fcntl.flock(fd, mode | fcntl.LOCK_NB)
94                    break
95                except BlockingIOError:
96                    if time.time() - t0 > wait:
97                        os.close(fd)
98                        self.ok = False
99                        for f in reversed(self.fds):
100                            os.close(f)
101                        self.fds = []
102                        return self
103                    time.sleep(0.2)
104            self.fds.append(fd)
105        return self
106
107    def __exit__(self, *a):
108        for fd in reversed(self.fds):
109            os.close(fd)
110        return 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)."""
115    global _hip
116    if _hip is None:
117        cands = [os.environ.get("TQENC_HIP_LIB", ""),
118                 str(pathlib.Path(__file__).resolve().parent.parent / "build-tqenc" / "libtqenc_hip.so")]
119        last = None
120        for c in cands:
121            if not c:
122                continue
123            try:
124                _hip = ctypes.CDLL(c)
125                break
126            except OSError as e:
127                last = e
128        if _hip is None:
129            raise 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,
132                                    ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_void_p,
133                                    ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int]
134    return _hip
135
136
137def encode(w: np.ndarray, t: int, h: np.ndarray | None = None, iters: int = 1, ncand: int = 1, exact: int = 0,
138           scale_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],
140    per-block error float64 [nblocks], total error, stats dict).  Error = sum h (w - decoded)^2 (h = 1 if None)."""
141    w = np.ascontiguousarray(w, dtype=np.float32)
142    if w.shape[-1] % BLOCK:
143        raise ValueError("last axis %d is not a multiple of 128" % w.shape[-1])
144    nb = w.size // BLOCK
145    out = np.zeros((nb, block_bytes(t)), dtype=np.uint8)
146    err = np.zeros(nb, dtype=np.float64)
147    stats = np.zeros(2, dtype=np.int64)
148    hp = None
149    if h is not None:
150        h = np.ascontiguousarray(h, dtype=np.float32)
151        if h.shape != w.shape:
152            raise ValueError("importance weights must have the shape of w")
153        hp = h.ctypes.data
154    if gpu:
155        if exact or t == TQ2_T:
156            raise ValueError("the GPU encoder has no exact search and no TQ2_T")
157        with _gpu_lock() as gl:
158            if gl.ok:
159                tot = hip_lib().tqh_encode(t, w.ctypes.data, hp, nb, out.ctypes.data, iters, ncand, scale_tries, 0,
160                                           err.ctypes.data, stats.ctypes.data, None, 0)
161                return out, err, tot, {"nonfinite_blocks": int(stats[0]), "zero_blocks": int(stats[1])}
162        threads = int(os.environ.get("TQENC_CPU_THREADS", threads or 24))   # the card stayed busy: the CPU encoder, same blocks
163    tot = lib().tqe_encode(t, w.ctypes.data, hp, nb, out.ctypes.data, iters, ncand, exact, scale_tries, threads,
164                           err.ctypes.data, stats.ctypes.data)
165    return 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)."""
170    packed = np.ascontiguousarray(packed, dtype=np.uint8)
171    bb = block_bytes(t)
172    if packed.size % bb:
173        raise ValueError("%d bytes is not a whole number of %s blocks" % (packed.size, TYPE_NAMES[t]))
174    nb = packed.size // bb
175    out = np.zeros(nb * BLOCK, dtype=np.float32)
176    lib().tqe_decode(t, packed.ctypes.data, nb, out.ctypes.data)
177    return 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."""
184    h = np.array([[1.0]])
185    while h.shape[0] < n:
186        h = np.block([[h, h], [h, -h]])
187    return (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."""
192    r = np.random.default_rng(seed)
193    return (r.integers(0, 2, size=width) * 2 - 1).astype(np.float32)
194
195
196def pack_signs(signs: np.ndarray) -> bytes:
197    return np.packbits((signs > 0).astype(np.uint8), bitorder="little").tobytes()
198
199
200def unpack_signs(b: bytes, width: int) -> np.ndarray:
201    bits = np.unpackbits(np.frombuffer(b, dtype=np.uint8), bitorder="little")[:width]
202    return 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).
207    The same function applied to an activation x gives U x."""
208    w = np.asarray(w, dtype=np.float32)
209    if signs is not None:
210        w = w * signs
211    shp = w.shape
212    return (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)."""
217    shp = w.shape
218    x = (np.asarray(w, dtype=np.float32).reshape(-1, BLOCK) @ hadamard_matrix()).reshape(shp)
219    return x * signs if signs is not None else x
220
221
222# ---------------------------------------------------------------------------------------------------- metrics
223
224def sqnr_db(ref: np.ndarray, approx: np.ndarray) -> float:
225    ref = np.asarray(ref, dtype=np.float64).ravel()
226    e = np.sum((ref - np.asarray(approx, dtype=np.float64).ravel()) ** 2)
227    return 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:
231    ref = np.asarray(ref, dtype=np.float64).ravel()
232    return 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:
245    import struct
246    sb = pack_signs(signs) if signs is not None else b""
247    with open(path, "wb") as f:
248        f.write(TQX_MAGIC + struct.pack("<IIIIII", TQX_VERSION, t, rows, cols, 1 if signs is not None else 0, len(sb)))
249        f.write(sb)
250        f.write(struct.pack("<I", BLOCK))
251        f.write(np.ascontiguousarray(packed, dtype=np.uint8).tobytes())
252
253
254def read_tqx(path):
255    import struct
256    data = open(path, "rb").read()
257    if data[:4] != TQX_MAGIC:
258        raise ValueError("not a TQXP file")
259    ver, t, rows, cols, flags, nsb = struct.unpack_from("<IIIIII", data, 4)
260    if ver == 1 and t in (TQK5X, TQK4X):
261        t += 2   # a version 1 file: the point table
262    elif ver != TQX_VERSION:
263        raise ValueError("unsupported TQXP version %d (this reader handles %d, and 1 for the point-table K5 / K4)" % (ver, TQX_VERSION))
264    if t not in KBITS:
265        raise ValueError("unknown trellis type %d" % t)
266    at = 4 + 24
267    signs = unpack_signs(data[at:at + nsb], cols) if flags & 1 else None
268    at += nsb
269    (blk,) = struct.unpack_from("<I", data, at)
270    at += 4
271    if blk != BLOCK:
272        raise ValueError("unsupported Hadamard block %d" % blk)
273    nb = rows * (cols // BLOCK)
274    packed = np.frombuffer(data, dtype=np.uint8, count=nb * block_bytes(t), offset=at).reshape(nb, block_bytes(t))
275    return t, rows, cols, packed, signs