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
2.7 KiB73 linesraw
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
7    W[:, 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:
19    from scipy.linalg import solve_triangular
20except Exception:   # numpy only: a small back substitution
21    solve_triangular = None
22
23
24def _solve_upper(A: np.ndarray, B: np.ndarray) -> np.ndarray:
25    if solve_triangular is not None:
26        return solve_triangular(A, B, lower=False)
27    return 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."""
32    H = np.asarray(H, dtype=np.float64).copy()
33    d = damp * float(np.mean(np.diag(H)))
34    H[np.diag_indices_from(H)] += d
35    Hinv = np.linalg.inv(H)
36    Hinv = (Hinv + Hinv.T) * 0.5
37    L = np.linalg.cholesky(Hinv)
38    return 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."""
43    n = R.shape[0]
44    out = []
45    for c0 in range(0, n, g):
46        c1 = c0 + g
47        out.append(_solve_upper(R[c0:c1, c0:c1], R[c0:c1, c1:]).astype(np.float32) if c1 < n else None)
48    return 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])."""
53    m, n = W.shape
54    B = n // 128
55    bb = tqenc.block_bytes(t)
56    Wc = np.ascontiguousarray(W, dtype=np.float32).copy()
57    packed = np.empty((m, B, bb), dtype=np.uint8)
58    dec = np.empty((m, n), dtype=np.float32)
59    kw = dict(iters=iters, ncand=ncand)
60    if gpu:
61        kw["gpu"] = True
62    else:
63        kw["threads"] = threads
64    for b in range(B):
65        c0, c1 = b * 128, (b + 1) * 128
66        blk = np.ascontiguousarray(Wc[:, c0:c1])
67        pk, _, _, _ = tqenc.encode(blk, t, **kw)
68        q = tqenc.decode(pk, t).reshape(m, 128)
69        packed[:, b] = pk
70        dec[:, c0:c1] = q
71        if fb[b] is not None:
72            Wc[:, c1:] -= (blk - q) @ fb[b]
73    return packed, dec