File size: 8,263 Bytes
6ec9472
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
"""Sub-2-bit weight codec: randomised Hadamard incoherence processing followed by
multi-stage residual vector quantisation on a shared (amortised-free) codebook.

Rate is controlled in 0.5 bit/weight steps by the number of residual stages:
each stage codes a d=16 subvector with an 8-bit index -> 0.5 bit/weight/stage.
"""
import math
import torch

D_SUB = 16          # subvector dimension
CB_BITS = 8         # bits per stage index
CB_SIZE = 1 << CB_BITS
BITS_PER_STAGE = CB_BITS / D_SUB   # 0.5 bit/weight


# ---------------------------------------------------------------- Hadamard
def _fwht(x):
    """In-place fast Walsh-Hadamard transform over the last dim (power of 2)."""
    n = x.shape[-1]
    assert n & (n - 1) == 0, f"dim {n} not a power of two"
    h = 1
    orig = x.shape
    x = x.reshape(-1, n).clone()
    while h < n:
        x = x.view(-1, n // (2 * h), 2, h)
        a = x[:, :, 0, :].clone()
        b = x[:, :, 1, :].clone()
        x[:, :, 0, :] = a + b
        x[:, :, 1, :] = a - b
        x = x.view(-1, n)
        h *= 2
    return (x / math.sqrt(n)).reshape(orig)


def _signs(n, seed, device, dtype):
    g = torch.Generator(device="cpu").manual_seed(seed)
    return (torch.randint(0, 2, (n,), generator=g).to(device=device,
            dtype=dtype) * 2 - 1)


def rht_forward(W, seed):
    sr = _signs(W.shape[1], seed, W.device, W.dtype)
    sl = _signs(W.shape[0], seed + 1, W.device, W.dtype)
    X = _fwht(W * sr)                    # right transform
    X = _fwht((X * sl.unsqueeze(1)).t().contiguous()).t().contiguous()
    return X


def rht_inverse(X, seed):
    sr = _signs(X.shape[1], seed, X.device, X.dtype)
    sl = _signs(X.shape[0], seed + 1, X.device, X.dtype)
    W = _fwht(X.t().contiguous()).t().contiguous() * sl.unsqueeze(1)
    W = _fwht(W) * sr
    return W


# ---------------------------------------------------------------- codebook
_CN = {}


def _cnorm(C):
    k = id(C)
    if k not in _CN or _CN[k][0] is not C:
        _CN[k] = (C, (C * C).sum(1).unsqueeze(0))
    return _CN[k][1]


def _assign(X, C, chunk=1 << 20):
    if X.shape[0] <= chunk:
        return (_cnorm(C) - 2.0 * (X @ C.t())).argmin(1)
    out = torch.empty(X.shape[0], dtype=torch.long, device=X.device)
    Cn = _cnorm(C)
    for s in range(0, X.shape[0], chunk):
        e = min(s + chunk, X.shape[0])
        out[s:e] = (Cn - 2.0 * (X[s:e] @ C.t())).argmin(1)
    return out


def rht_hessian(H, seed):
    """Transform an input-side Hessian into the RHT basis: H' = T^T H T with
    T = diag(s_r) * Hadamard (orthogonal, symmetric Hadamard)."""
    s = _signs(H.shape[0], seed, H.device, H.dtype)
    A = H * s.unsqueeze(0) * s.unsqueeze(1)
    A = _fwht(A)
    A = _fwht(A.t().contiguous()).t().contiguous()
    return A


# ---------------------------------------------------------------- quantiser
def vq(V, codebooks, stages, refine=1):
    """Multi-stage residual VQ of [N, D_SUB] rows, with optional coordinate
    refinement: each stage index is re-solved against the residual left by all
    the other stages, which recovers part of the greedy-encoding loss."""
    Q = torch.zeros_like(V)
    parts = []
    for s in range(stages):
        C = codebooks[s]
        idx = _assign(V - Q, C)
        p = C[idx]
        parts.append(p)
        Q = Q + p
    for _ in range(refine):
        for s in range(stages):
            Q = Q - parts[s]
            idx = _assign(V - Q, codebooks[s])
            parts[s] = codebooks[s][idx]
            Q = Q + parts[s]
    return Q


def _block_ldl(H, blk):
    """H = L D L^T with L block-unit-lower-triangular (blocks of size blk).

    The per-block inverses are batched into a single call rather than looped.
    """
    n = H.shape[0]
    C = torch.linalg.cholesky(H)
    K = n // blk
    diag = torch.stack([C[k * blk:(k + 1) * blk, k * blk:(k + 1) * blk]
                        for k in range(K)])
    dinv = torch.linalg.inv(diag)
    Binv = torch.zeros_like(C)
    idx = torch.arange(blk, device=H.device)
    for k in range(K):
        Binv[k * blk + idx[:, None], k * blk + idx[None, :]] = dinv[k]
    return C @ Binv


def prepare_hessian(H, seed, rht_on=True, blk=D_SUB, damp=0.01):
    """Rotate, damp and block-LDL-factorise a Hessian once, so that every linear
    sharing this input reuses the factorisation."""
    dev = H.device
    Hf = H.float().clone()
    dead = torch.diag(Hf) <= 0
    if dead.any():
        Hf[dead, dead] = 1.0
    Hf += torch.eye(Hf.shape[0], device=dev) * (damp * torch.diag(Hf).mean())
    Hr = rht_hessian(Hf, seed) if rht_on else Hf
    return _block_ldl(Hr, blk), dead


def ldlq_quantize(W, L, dead, codebooks, stages, seed=1234, rht_on=True,
                  blk=D_SUB, refine=0):
    """Hessian-aware quantisation: minimise ||(W-What) X||_F with H = X X^T,
    by block-LDL error feedback over blk-column groups, each group coded by the
    residual VQ. `L`/`dead` come from `prepare_hessian` and are shared by all
    linears reading the same input."""
    dt = W.dtype
    Wf = W.float()
    if dead is not None and dead.any():
        Wf = Wf.clone()
        Wf[:, dead] = 0.0

    X = rht_forward(Wf, seed) if rht_on else Wf
    scale = X.pow(2).mean(dim=1, keepdim=True).sqrt().clamp_min(1e-8)
    Xn = X / scale

    o, i = Xn.shape
    K = i // blk
    Q = torch.zeros_like(Xn)
    E = torch.zeros_like(Xn)
    for k in range(K - 1, -1, -1):
        s = slice(k * blk, (k + 1) * blk)
        tgt = Xn[:, s]
        if k + 1 < K:
            tgt = tgt + E[:, (k + 1) * blk:] @ L[(k + 1) * blk:, s]
        Q[:, s] = vq(tgt.reshape(-1, D_SUB), codebooks, stages,
                     refine).reshape(o, blk)
        E[:, s] = Xn[:, s] - Q[:, s]

    Xq = Q * scale
    What = rht_inverse(Xq, seed) if rht_on else Xq
    bits = stages * BITS_PER_STAGE + 16.0 / i
    return What.to(dt), dict(bits=bits, stages=stages)


def quantize(W, codebooks, stages, seed=1234, rht_on=True, refine=1):
    """Quantise [out,in] weight matrix at `stages`*0.5 bits/weight, ignoring
    activation statistics (the data-free ablation of `ldlq_quantize`)."""
    Wf = W.float()
    X = rht_forward(Wf, seed) if rht_on else Wf
    o, i = X.shape
    scale = X.pow(2).mean(dim=1, keepdim=True).sqrt().clamp_min(1e-8)
    Xn = X / scale
    Q = vq(Xn.reshape(-1, D_SUB), codebooks, stages, refine).reshape(o, i)
    Xq = Q * scale
    What = rht_inverse(Xq, seed) if rht_on else Xq
    bits = stages * BITS_PER_STAGE + 16.0 / i          # + fp16 row scale
    return What.to(W.dtype), dict(bits=bits, stages=stages)


def build_codebooks(max_stages=6, device="cpu", seed=0):
    """Stage-0 codebook on Gaussian data; each later stage on the residual
    distribution produced by the preceding stages (so shapes adapt)."""
    g = torch.Generator(device="cpu").manual_seed(seed)
    X = torch.randn(400_000, D_SUB, generator=g).to(device)
    cbs, R = [], X.clone()
    for s in range(max_stages):
        C = _kmeans(R, CB_SIZE, iters=35, seed=seed + s, device=device)
        cbs.append(C)
        R = R - C[_assign(R, C)]
    return cbs


def _kmeans(X, size, iters, seed, device):
    g = torch.Generator(device="cpu").manual_seed(seed)
    n = X.shape[0]
    C = X[torch.randperm(n, generator=g)[:size]].clone()
    for _ in range(iters):
        idx = _assign(X, C)
        C_new = torch.zeros_like(C)
        cnt = torch.zeros(size, device=device)
        C_new.index_add_(0, idx, X)
        cnt.index_add_(0, idx, torch.ones(n, device=device))
        dead = cnt == 0
        C_new[~dead] /= cnt[~dead].unsqueeze(1)
        if dead.any():
            C_new[dead] = X[torch.randint(0, n, (int(dead.sum()),),
                                          generator=g)]
        C = C_new
    return C


# ---------------------------------------------------------------- baseline
def rtn(W, bits, group=128):
    """Round-to-nearest uniform baseline with per-group asymmetric scales."""
    o, i = W.shape
    Wf = W.float().reshape(o, i // group, group)
    mn = Wf.amin(-1, keepdim=True)
    mx = Wf.amax(-1, keepdim=True)
    n = 2 ** bits - 1
    s = ((mx - mn) / n).clamp_min(1e-9)
    q = ((Wf - mn) / s).round().clamp(0, n)
    Wq = (q * s + mn).reshape(o, i)
    eff = bits + 2 * 16.0 / group
    return Wq.to(W.dtype), dict(bits=eff)