File size: 7,423 Bytes
bdf5f4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
quant_correct.py — can the framework absorb its own quantization error?

Three mechanisms tested separately on real Llama-3.2-3B weights, because they
are NOT the same thing and only some of them work:

  A. RESIDUAL COUPLING (works, and is the good one).
     Quantization leaves R = W - W_q. R is not noise -- it is a matrix, and a
     low-rank piece of it carries most of its action. Store rank-k U,V and the
     projection becomes

         z = W_q x  +  U (V x)

     which in the framework is not a correction term bolted on: it is a SECOND,
     much smaller resonator sheet driven by the same input, summed into the same
     equilibrium. Error correction as additional coupling.

  B. THE GAIN MEDIUM (works, but only on one component of the error).
     RMSNorm-as-saturable-gain preserves direction exactly and clamps total
     power. Any error that is a pure magnitude error is therefore REMOVED. Error
     that rotates the state is not. Measured here as the split between the two.

  C. RELAXATION ITSELF (does NOT work -- included to kill the idea).
     dz/dt = -gamma z + W_q x settles to W_q x / gamma. The fixed point of the
     WRONG coupling is the wrong answer. More steps converge harder onto it.

    python3 quant_correct.py
"""
import json, os, sys, time
import numpy as np

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from bqsm_llama import Safetensors, BASE, gain_norm, relax

CFG = json.load(open(os.path.join(BASE, "config.json")))
EPS = CFG["rms_norm_eps"]
D = CFG["hidden_size"]


def int_percol(W, bits):
    n = (1 << (bits - 1)) - 1
    s = np.abs(W).max(axis=1, keepdims=True) / n
    s[s == 0] = 1.0
    q = np.clip(np.rint(W / s), -n, n).astype(np.int8 if bits <= 8 else np.int16)
    return q, s.astype(np.float32)


def rsvd(R, k, over=8, seed=0):
    """Randomized SVD -- an exact SVD of 8192x3072 is minutes, this is seconds
    and the tail we are discarding is exactly the part we do not keep anyway."""
    rng = np.random.default_rng(seed)
    Om = rng.standard_normal((R.shape[1], k + over)).astype(np.float32)
    Y = R @ Om
    Q, _ = np.linalg.qr(Y)
    B = Q.T @ R
    Ub, S, Vt = np.linalg.svd(B, full_matrices=False)
    U = (Q @ Ub[:, :k]) * S[:k]
    return U.astype(np.float32), Vt[:k].astype(np.float32)


def main():
    st = Safetensors(BASE)
    pre = "model."
    emb = st.get(pre + "embed_tokens.weight")
    ids = [128000, 791, 6864, 315, 9822, 374]
    X = emb[ids].astype(np.float32)

    L = 13
    p = f"{pre}layers.{L}."
    wn = st.get(p + "post_attention_layernorm.weight")
    Xn = X / np.sqrt((X * X).mean(-1, keepdims=True) + EPS) * wn
    W = st.get(p + "mlp.gate_proj.weight").astype(np.float32)
    ref = Xn @ W.T
    nrm = np.linalg.norm(ref)
    out_dim, in_dim = W.shape
    full_bits = W.size * 16

    def rel(g):
        return float(np.linalg.norm(g - ref) / nrm)

    print(f"Llama-3.2-3B  layer {L} mlp.gate_proj {W.shape}  real activations\n")

    # ================= A. residual coupling =================
    print("  A. RESIDUAL COUPLING  —  z = W_q x + U(V x)\n")
    print(f"  {'encoding':<34}{'rank':>6}{'bytes vs bf16':>15}{'rel-err':>11}{'corr':>10}")
    print("  " + "-" * 78)
    for bits in (8, 4, 3):
        q, s = int_percol(W, bits)
        Wq = (q.astype(np.float32) * s)
        base = Xn @ Wq.T
        wbits = W.size * bits + out_dim * 32
        print(f"  {'int%d + per-column scale' % bits:<34}{'-':>6}"
              f"{100*wbits/full_bits:>14.1f}%{rel(base):>11.2e}"
              f"{float(np.corrcoef(base.ravel(), ref.ravel())[0,1]):>10.6f}")
        R = W - Wq
        for k in (16, 32, 64, 128):
            U, V = rsvd(R, k)
            got = base + (Xn @ V.T) @ U.T
            kb = wbits + k * (out_dim + in_dim) * 16
            print(f"  {'  + rank-%d residual sheet' % k:<34}{k:>6}"
                  f"{100*kb/full_bits:>14.1f}%{rel(got):>11.2e}"
                  f"{float(np.corrcoef(got.ravel(), ref.ravel())[0,1]):>10.6f}")
        print()

    # ================= B. gain medium =================
    print("  B. GAIN MEDIUM  —  does the norm remove quantization error?\n")
    q8, s8 = int_percol(W, 8)
    q4, s4 = int_percol(W, 4)
    print(f"  {'encoding':<24}{'before norm':>14}{'after norm':>13}{'removed':>11}"
          f"{'  split (magnitude / direction)'}")
    print("  " + "-" * 96)
    for nm, (qq, ss) in (("int8", (q8, s8)), ("int4", (q4, s4))):
        g = Xn @ (qq.astype(np.float32) * ss).T
        e0 = rel(g)
        w1 = np.ones(g.shape[-1], np.float32)
        a = gain_norm(g, w1, EPS, steps=400)
        b = gain_norm(ref, w1, EPS, steps=400)
        e1 = float(np.linalg.norm(a - b) / np.linalg.norm(b))
        # split the raw error into a pure-scale part and a rotation part
        alpha = float((g.ravel() @ ref.ravel()) / (ref.ravel() @ ref.ravel()))
        mag = abs(alpha - 1.0)
        rot = float(np.linalg.norm(g - alpha * ref) / nrm)
        print(f"  {nm:<24}{e0:>14.2e}{e1:>13.2e}{100*(1-e1/e0):>10.1f}%"
              f"    {mag:.2e} / {rot:.2e}")

    # ================= C. relaxation =================
    print("\n  C. RELAXATION  —  do more steps correct a wrong coupling?\n")
    Wq4 = (q4.astype(np.float32) * s4)
    print(f"  {'relax steps':<24}{'rel-err vs true W':>20}")
    print("  " + "-" * 46)
    for steps in (10, 60, 240, 1000):
        got = relax(Wq4, Xn, steps)
        print(f"  {steps:<24}{rel(got):>20.2e}")
    print(f"  {'exact fixed point':<24}{rel(Xn @ Wq4.T):>20.2e}")

    print("""
  VERDICT — ALL THREE FAIL. Measured, not argued.

  A FAILS. This section was written expecting it to work, and the numbers say
    otherwise: rank-128 moves int4 from 1.72e-01 to 1.65e-01, a 4% error
    reduction for 5.7% more bytes. The reason is the residual's SPECTRUM. For
    a per-column int4 quantizer the top 128 of 1024 singular values hold 50.2%
    of the residual energy -- which is what a flat spectrum looks like. The
    residual is rounding noise, and rounding noise has no low-rank structure
    for a second coupling sheet to carry. "The residual is a matrix, not noise"
    was the assumption; it is measurably false.

  B FAILS in practice, though the mechanism is real. The gain medium removes
    magnitude error exactly. But splitting the int8 error gives 1.36e-05
    magnitude against 9.53e-03 direction: it is 99.9% rotational. The norm
    removes -0.3%. Genuine error correction with essentially nothing to correct.

  C CANNOT work, by construction. Relaxation converges to the fixed point of
    the coupling it is given. Wrong coupling, wrong fixed point: 1.72e-01 at 10
    steps and 1.72e-01 at 1000. More settling converges onto the wrong answer
    more precisely. Any claim that settling 'heals' quantization error is false.

  WHAT IS LEFT. Nothing downstream recovers quantization error, so the only
  lever is quantizing better in the first place -- choosing the quantized values
  so the OUTPUT error cancels (GPTQ-style error feedback against a Hessian),
  rather than minimising weight error and repairing afterwards. Crude
  activation-aware rescaling was tried and gives 1.02x, i.e. nothing.

  OPERATING POINT: int8 + per-column scale. 5.6 GB -> 2.8 GB, rel-err 9.5e-03,
  corr 0.999954, and it fits in RAM on this box. Below int8 the error is real
  and the framework does not get it back.""")


if __name__ == "__main__":
    main()