Download smq.py from CompressedGemma/SMQ-Quantize-0.1: direct link, hf CLI and curl.
- Browser
- Download file 12.1 kB
-
https://huggingface.co/CompressedGemma/SMQ-Quantize-0.1/resolve/main/smq.py
- Command line
-
hf download hf://CompressedGemma/SMQ-Quantize-0.1/smq.py
-
curl -L -o smq.py https://huggingface.co/CompressedGemma/SMQ-Quantize-0.1/resolve/main/smq.py
12.1 kB
| """SMQ solver pieces under the matched metric: code projection + closed-form (d, m). | |
| E = sum_i w_i e_i^2 + sum_{k=1..8} lambda_k * sum_j G_kj^2, e = x - xhat | |
| The whole matched metric is a SINGLE quadratic form. Each fold level k is a | |
| strided group-sum operator A_k (element i belongs to group i mod (256/2^k)), | |
| and sum_j G_kj^2 = ||A_k e||^2 = e' A_k' A_k e, so | |
| E = e' M e, M = diag(w) + L, L = sum_k lambda_k A_k' A_k (fixed 256x256) | |
| L is precomputed once per (lam, dtype, device) by _fold_gram and every | |
| objective evaluation, gradient tile, and Hessian/Gram entry is then just a | |
| bilinear form with L (one matmul), with no per-level fold loops. | |
| Per pass: project every code at once (Newton form, e_i = x_i - s_i q_i + | |
| m lm_i, s_i = d ls_i, Lam = sum_k lambda_k). Since (L e)_i equals | |
| sum_k lambda_k G_k(i), the per-element coupled gradient tile is e @ L: | |
| q_i <- clip(round(q_i + (w_i e_i + (e @ L)_i) / ((w_i + Lam) s_i)), 0, 3) | |
| After the pass, e is rebuilt from the new codes and the next pass re-evaluates. | |
| """ | |
| from __future__ import annotations | |
| QK = 256 | |
| NSUB = 16 | |
| _TINY = 1.0e-30 | |
| def _fold_gram(lam): | |
| """Single-matrix form of the spectral penalty: L = sum_k lambda_k A_k' A_k. | |
| A_k is the strided fold operator with (A_k e)_r = sum over elements i with | |
| i mod (256/2^k) == r, so (A_k' A_k)[i, j] = [i mod (256/2^k) == j mod | |
| (256/2^k)]. The full matched metric of the module docstring is then | |
| E = e' (diag(w) + L) e — one quadratic form, no fold loops. | |
| """ | |
| import torch | |
| ids = torch.arange(QK, device=lam.device) | |
| L = torch.zeros(QK, QK, dtype=lam.dtype, device=lam.device) | |
| for k in range(1, 9): | |
| r = ids.remainder(QK >> k) | |
| L = L + lam[k - 1] * (r[:, None] == r[None, :]).to(L.dtype) | |
| return L | |
| def _objective_quad(e, w, L): | |
| """Matched metric E per block as one quadratic form: (w e^2) + e' L e -> (n,).""" | |
| return (w * e * e).sum(dim=1) + (e @ L * e).sum(dim=1) | |
| def _codes_pass(x, w, e, d, m, ls_e, lm_e, q, L, lam_sum): | |
| """One code-projection pass over all 256 elements. Returns (q, e).""" | |
| import torch | |
| S = e @ L # == sum_k lambda_k G_k(i) tiled per element | |
| step = d[:, None] * ls_e | |
| curv = w + lam_sum | |
| good = (step > _TINY) & (curv > _TINY) | |
| safe = torch.where(good, curv * step, torch.ones_like(step)) | |
| ratio = q + (w * e + S) / safe | |
| q_new = torch.where(good, torch.clamp(torch.round(ratio), 0.0, 3.0), q) | |
| e_new = x - d[:, None] * ls_e * q_new + m[:, None] * lm_e | |
| return q_new, e_new | |
| def _dm_system(x, w, a, b, L): | |
| """2x2 matched-metric WLS system for (d, m), one quadratic form, no folds. | |
| a = ls_e * q (grid slope), b = lm_e (grid offset, r_i = 1); returns | |
| H11, H12, H22, g1, g2 for E = th' H th - 2 th' g + c, th = (d, m). | |
| Every fold-level term is a bilinear form u' L v of the single matrix L: | |
| sum_k lam_k (A_k u) . (A_k v) = u' L v. | |
| """ | |
| H11 = (w * a * a).sum(1) + (a @ L * a).sum(1) | |
| H12 = -((w * a * b).sum(1) + (a @ L * b).sum(1)) | |
| H22 = (w * b * b).sum(1) + (b @ L * b).sum(1) | |
| g1 = (w * x * a).sum(1) + (x @ L * a).sum(1) | |
| g2 = -((w * x * b).sum(1) + (x @ L * b).sum(1)) | |
| return H11, H12, H22, g1, g2 | |
| def _solve2(H11, H12, H22, g1, g2): | |
| """Solve a batch of 2x2 systems H th = g with a validity mask.""" | |
| import torch | |
| det = H11 * H22 - H12 * H12 | |
| ok = (det > _TINY) & torch.isfinite(det) & torch.isfinite(g1) & torch.isfinite(g2) | |
| det_s = torch.where(ok, det, torch.ones_like(det)) | |
| v1 = (H22 * g1 - H12 * g2) / det_s | |
| v2 = (H11 * g2 - H12 * g1) / det_s | |
| ok = ok & torch.isfinite(v1) & torch.isfinite(v2) | |
| return ok, v1, v2 | |
| def _quad2(H11, H12, H22, g1, g2, d, m): | |
| """Constant-free value of the 2-D quadratic represented by _dm_system.""" | |
| return ( | |
| H11 * d * d + 2.0 * H12 * d * m + H22 * m * m | |
| - 2.0 * g1 * d - 2.0 * g2 * m | |
| ) | |
| def _solve2_constrained( | |
| H11, H12, H22, g1, g2, d_current, m_current, d_floor=_TINY | |
| ): | |
| """Minimize the convex 2-D quadratic subject to d >= d_floor and m >= 0. | |
| The candidate set consists of the feasible unconstrained optimum, both | |
| one-dimensional boundary optima, the corner (included by clamping the | |
| boundary solutions), and the current feasible point as a numerical | |
| fallback. Comparing the original quadratic makes this valid for singular | |
| positive-semidefinite systems as well as nonsingular systems. | |
| """ | |
| import torch | |
| d0 = torch.clamp(torch.nan_to_num(d_current, nan=d_floor, posinf=65504.0, neginf=d_floor), min=d_floor) | |
| m0 = torch.clamp(torch.nan_to_num(m_current, nan=0.0, posinf=65504.0, neginf=0.0), min=0.0) | |
| best_d, best_m = d0, m0 | |
| best_v = _quad2(H11, H12, H22, g1, g2, best_d, best_m) | |
| best_v = torch.where(torch.isfinite(best_v), best_v, torch.full_like(best_v, float("inf"))) | |
| # Interior stationary point. | |
| ok_i, d_i, m_i = _solve2(H11, H12, H22, g1, g2) | |
| ok_i = ok_i & (d_i >= d_floor) & (m_i >= 0.0) | |
| v_i = _quad2(H11, H12, H22, g1, g2, d_i, m_i) | |
| ok_i = ok_i & torch.isfinite(v_i) | |
| take = ok_i & (v_i < best_v) | |
| best_d = torch.where(take, d_i, best_d) | |
| best_m = torch.where(take, m_i, best_m) | |
| best_v = torch.where(take, v_i, best_v) | |
| # Boundary m = 0: optimize d on its feasible half-line. | |
| h11_ok = torch.isfinite(H11) & (H11 > _TINY) | |
| d_m0 = torch.where(h11_ok, torch.clamp(g1 / torch.where(h11_ok, H11, torch.ones_like(H11)), min=d_floor), d0) | |
| m_m0 = torch.zeros_like(m0) | |
| v_m0 = _quad2(H11, H12, H22, g1, g2, d_m0, m_m0) | |
| ok_m0 = torch.isfinite(v_m0) & torch.isfinite(d_m0) | |
| take = ok_m0 & (v_m0 < best_v) | |
| best_d = torch.where(take, d_m0, best_d) | |
| best_m = torch.where(take, m_m0, best_m) | |
| best_v = torch.where(take, v_m0, best_v) | |
| # Boundary d = d_floor: optimize the nonnegative offset. | |
| h22_ok = torch.isfinite(H22) & (H22 > _TINY) | |
| h22_safe = torch.where(h22_ok, H22, torch.ones_like(H22)) | |
| m_df = torch.where( | |
| h22_ok, | |
| torch.clamp((g2 - H12 * d_floor) / h22_safe, min=0.0), | |
| m0, | |
| ) | |
| d_df = torch.full_like(d0, float(d_floor)) | |
| v_df = _quad2(H11, H12, H22, g1, g2, d_df, m_df) | |
| ok_df = torch.isfinite(v_df) & torch.isfinite(m_df) | |
| take = ok_df & (v_df < best_v) | |
| best_d = torch.where(take, d_df, best_d) | |
| best_m = torch.where(take, m_df, best_m) | |
| return best_d, best_m | |
| def _dm_resolve(x, w, q, ls_e, lm_e, d, m, L): | |
| """Closed-form matched-metric (d, m) for ALL blocks at once, no iteration. | |
| With codes and (ls, lm) fixed, e_i = x_i - d a_i + m b_i is affine in | |
| (d, m), a_i = ls_i q_i, b_i = lm_i, so the single quadratic E = e' M e | |
| (M = diag(w) + L, all eight fold levels included) is an exact 2x2 | |
| quadratic in th = (d, m): E = th' H th - 2 th' g + c. The solution is | |
| th = H^-1 g (Cramer's rule), constrained to d > 0, m >= 0. | |
| Returns continuous (d, m); the caller rounds to fp16 and guards on E. | |
| """ | |
| a = ls_e * q | |
| H11, H12, H22, g1, g2 = _dm_system(x, w, a, lm_e, L) | |
| return _solve2_constrained(H11, H12, H22, g1, g2, d, m) | |
| def _integer_lattice_min_2d(H11, H12, H22, g1, g2, current_s, current_t, upper=15): | |
| """Exact minimum of a convex 2-D quadratic on {0..upper}^2. | |
| Enumerate the 16 (or ``upper+1``) possible first coordinates. For each, | |
| the conditional optimum in t is one-dimensional and convex, so its integer | |
| minimum is floor(t*) or ceil(t*) (with clipping at the boundaries). This | |
| gives at most 2*(upper+1) candidates instead of a full square lattice scan. | |
| """ | |
| import torch | |
| cur_s = torch.clamp(torch.round(current_s), 0.0, float(upper)) | |
| cur_t = torch.clamp(torch.round(current_t), 0.0, float(upper)) | |
| s_grid = torch.arange(upper + 1, device=H11.device, dtype=H11.dtype).view(1, -1) | |
| s_grid = s_grid.expand(H11.shape[0], -1) | |
| h22_ok = torch.isfinite(H22) & (H22 > _TINY) | |
| h22_safe = torch.where(h22_ok, H22, torch.ones_like(H22)) | |
| t_star = torch.clamp( | |
| (g2[:, None] - H12[:, None] * s_grid) / h22_safe[:, None], | |
| 0.0, float(upper), | |
| ) | |
| t_lo = torch.floor(t_star) | |
| t_hi = torch.ceil(t_star) | |
| # For a PSD quadratic H22=0 implies H12=0; t is then unidentifiable. | |
| t_lo = torch.where(h22_ok[:, None], t_lo, cur_t[:, None]) | |
| t_hi = torch.where(h22_ok[:, None], t_hi, cur_t[:, None]) | |
| s_candidates = torch.cat((s_grid, s_grid), dim=1) | |
| t_candidates = torch.cat((t_lo, t_hi), dim=1) | |
| values = _quad2( | |
| H11[:, None], H12[:, None], H22[:, None], | |
| g1[:, None], g2[:, None], s_candidates, t_candidates, | |
| ) | |
| values = torch.where(torch.isfinite(values), values, torch.full_like(values, float("inf"))) | |
| best_idx = torch.argmin(values, dim=1, keepdim=True) | |
| best_val = values.gather(1, best_idx).squeeze(1) | |
| best_s = s_candidates.gather(1, best_idx).squeeze(1) | |
| best_t = t_candidates.gather(1, best_idx).squeeze(1) | |
| # Retain the current lattice point if roundoff makes its evaluated value | |
| # lower than the analytically enumerated conditional minima. | |
| cur_val = _quad2(H11, H12, H22, g1, g2, cur_s, cur_t) | |
| keep_cur = (~torch.isfinite(best_val)) | (cur_val < best_val) | |
| return torch.where(keep_cur, cur_s, best_s), torch.where(keep_cur, cur_t, best_t), torch.minimum(cur_val, best_val) | |
| def _ls_lm_resolve(x, w, e, d, m, q, ls, lm, lam): | |
| """Closed-form matched-metric (ls, lm) for ALL 16 sub-blocks of ALL blocks at once. | |
| For sub-block j, e_i = x_i - Ls alpha_i + Lm beta (alpha_i = d q_i, beta = m) | |
| is affine in theta = (Ls, Lm). A level-k group g meets sub-block j in A_g = | |
| sum alpha (and B_g = |g n j| m) and its group sum is T_g - Ls A_g + Lm B_g, | |
| where T_g = G_g + Ls_cur A_g - Lm_cur B_g carries every other sub-block's | |
| current contribution. So the matched E restricted to sub-block j is an exact | |
| 2x2 quadratic th' H th - 2 th' g + c with | |
| H11 = sum w alpha^2 + sum_k lam_k sum_g A_g^2 H12 = -(sum w alpha beta + sum_k lam_k sum_g A_g B_g) | |
| H22 = sum w beta^2 + sum_k lam_k sum_g B_g^2 | |
| g1 = sum w x alpha + sum_k lam_k sum_g T_g A_g g2 = -(sum w x beta + sum_k lam_k sum_g T_g B_g) | |
| Levels 1-4 (stride >= 16): each group holds one element of j. Levels 5-8 | |
| (stride 8, 4, 2, 1): each group holds 16/stride elements of j. | |
| The integer minimum on {0..15}^2 is then enumerated exactly (no 256-point scan). | |
| All sub-blocks are solved against the CURRENT state of the others. | |
| The metric is still the single quadratic E = e' (diag(w) + L) e; this solver | |
| keeps the explicit fold form because its per-sub-block "state of the others" | |
| correction T_g does not reduce to cheap bilinear forms with L. | |
| """ | |
| import torch | |
| n = x.shape[0] | |
| al = (d[:, None] * q).reshape(n, NSUB, 16) | |
| be = m[:, None, None] | |
| xs = x.reshape(n, NSUB, 16) | |
| ws = w.reshape(n, NSUB, 16) | |
| H11 = (ws * al * al).sum(2) | |
| H12 = -(ws * al * be).sum(2) | |
| H22 = (ws * be * be).sum(2) | |
| g1 = (ws * xs * al).sum(2) | |
| g2 = -(ws * xs * be).sum(2) | |
| ids = torch.arange(QK, device=x.device).reshape(NSUB, 16) | |
| ls3 = ls[:, :, None] | |
| lm3 = lm[:, :, None] | |
| for k in range(1, 9): | |
| S = QK >> k | |
| Gk = e.reshape(n, 1 << k, S).sum(1) # (n, S) group sums, indexed by residue | |
| if S >= 16: | |
| A = al | |
| B = be + torch.zeros_like(al) | |
| Gc = Gk[:, ids % S] # (n, 16, 16): group sum of each element's own group | |
| else: | |
| A = al.reshape(n, NSUB, 16 // S, S).sum(2) # (n, 16, S) | |
| B = be * (16 // S) + torch.zeros_like(A) | |
| Gc = Gk[:, None, :] + torch.zeros_like(A) | |
| T = Gc + ls3 * A - lm3 * B | |
| c = lam[k - 1] | |
| H11 = H11 + c * (A * A).sum(2) | |
| H12 = H12 - c * (A * B).sum(2) | |
| H22 = H22 + c * (B * B).sum(2) | |
| g1 = g1 + c * (T * A).sum(2) | |
| g2 = g2 - c * (T * B).sum(2) | |
| s_new, t_new, _ = _integer_lattice_min_2d( | |
| H11.reshape(-1), H12.reshape(-1), H22.reshape(-1), g1.reshape(-1), g2.reshape(-1), | |
| ls.reshape(-1), lm.reshape(-1), | |
| ) | |
| return s_new.reshape(n, NSUB), t_new.reshape(n, NSUB) | |