#!/usr/bin/env python3 """Bake an INT4 lm_head (GPTQ and RTN) and an INT8 embedding for LFM3-1.7B, after the B65 head bake (github.com/launch80/B65, bake/bake_quant.py + bake_gptq_resume.py, MIT; as adapted by Wrapzii). - Activations: the lm_head input = output of the final norm (`embedding_norm`) of the model whose body is the GPTQ INT4 checkpoint (weights dequantized exactly as served), over the calibration set. - Hessian H = sum x^T x (fp32); every 64th row is held out (max 8192): half of them pick the GPTQ setting from a small grid (damp, static act-order, MSE-clipped scales), the other half are reported. - GPTQ: symmetric int4, group 128 (contiguous groups, no runtime g_idx), lazy block 128 = group, output rows in chunks. B65's setting is damp 1%, natural column order, scale = absmax/7 of the error-compensated group; the grid adds damp 0.1-10%, static act-order and clip-searched scales. Scales are rounded to BF16 *before* choosing codes (the stored scale is what vLLM dequantizes with). - RTN: same scale rule on the original weights, no error propagation. - Embedding: INT8 symmetric, one BF16 scale per row (absmax/127, rounded before coding). Everything is written in compressed-tensors pack-quantized layout (weight_packed int32 packed along the input dim, weight_scale, weight_shape), i.e. what vLLM's CompressedTensorsWNA16 (lm_head) and CompressedTensorsEmbeddingWNA16Int (embedding) load. python3 bake_head_embed.py MODEL_DIR BODY_DIR CALIB.pt OUT_DIR [DEVICE=xpu] -> OUT_DIR/{head_gptq,head_rtn,embed_int8}.safetensors, bake_manifest.json """ import glob, json, sys, time import torch from compressed_tensors.compressors.pack_quantized.helpers import pack_to_int32, unpack_from_int32 from safetensors import safe_open from safetensors.torch import save_file from transformers import AutoModelForCausalLM model_dir, body_dir, calib, out_dir = sys.argv[1:5] dev = sys.argv[5] if len(sys.argv) > 5 else "xpu" G, DAMP, EVERY, EVAL_CAP, CHUNK = 128, 0.01, 64, 8192, 8192 torch.manual_seed(0) model = AutoModelForCausalLM.from_pretrained(model_dir, dtype=torch.bfloat16, trust_remote_code=True) def dequant(packed, scale, shape): q = unpack_from_int32(packed, 4, torch.Size(shape.tolist()), packed_dim=1).float() return (q.view(q.shape[0], -1, G) * scale.float()[:, :, None]).view(q.shape) # body weights exactly as the INT4 checkpoint stores them mods = dict(model.named_modules()) n_body = 0 for f in sorted(glob.glob(f"{body_dir}/*.safetensors")): with safe_open(f, "pt") as sf: for k in sf.keys(): if k.endswith(".weight_packed"): base = k[: -len(".weight_packed")] w = dequant(sf.get_tensor(k), sf.get_tensor(base + ".weight_scale"), sf.get_tensor(base + ".weight_shape")) mods[base].weight.data.copy_(w.to(torch.bfloat16)) n_body += 1 print(f"loaded {n_body} INT4 body linears from {body_dir}", flush=True) model.to(dev).eval() # --- Hessian of the lm_head input K = model.config.hidden_size H = torch.zeros(K, K, dtype=torch.float32, device=dev) held, rows, row_id = [], 0, 0 samples = torch.load(calib) t0 = time.time() with torch.no_grad(): for s in samples: x = model.model(input_ids=s.to(dev)).last_hidden_state[0].float() # final-norm output idx = torch.arange(row_id, row_id + x.shape[0], device=dev) row_id += x.shape[0] is_held = idx % EVERY == 0 H += x[~is_held].T @ x[~is_held] rows += int((~is_held).sum()) if sum(h.shape[0] for h in held) < EVAL_CAP: held.append(x[is_held]) Xe = torch.cat(held)[:EVAL_CAP] print(f"Hessian from {rows} rows, {Xe.shape[0]} held out, {time.time() - t0:.0f} s", flush=True) W = model.model.embed_tokens.weight.detach().float() # tied: lm_head == embed_tokens (V, K) V = W.shape[0] def scale_of(block, qmax): return (block.abs().amax(-1) / qmax).clamp_min(1e-8).to(torch.bfloat16).float() CLIP = [1.0, 0.95, 0.9, 0.85, 0.8, 0.75] def mse_scale(Wg): """Per-(row, group) int4 scale: absmax/7 shrunk by the clip factor with the lowest squared error.""" best, best_err = None, None for c in CLIP: s = scale_of(Wg, 7 / c) err = ((Wg - torch.clamp(torch.round(Wg / s[..., None]), -8, 7) * s[..., None]) ** 2).sum(-1) if best is None: best, best_err = s, err else: better = err < best_err best, best_err = torch.where(better, s, best), torch.where(better, err, best_err) return best def rtn_int4(W): Wg = W.view(W.shape[0], -1, G) s = scale_of(Wg, 7) return torch.clamp(torch.round(Wg / s[..., None]), -8, 7).view(W.shape), s def gptq_int4(W, H, damp=DAMP, actorder=False, mse=False): """GPTQ, symmetric int4, contiguous groups of G (no runtime g_idx). actorder=False: columns in natural order, each group's scale from the error-compensated block (B65). actorder=True ("static" act-order): columns processed by descending diag(H), group scales fixed up front from the original weights (as llm-compressor's actorder="static"). mse: clip-searched scales instead of plain absmax/7.""" H = H.clone() dead = torch.diag(H) == 0 H[dead, dead] = 1 H += torch.eye(K, device=H.device) * damp * torch.diag(H).mean() perm = torch.argsort(torch.diag(H), descending=True) if actorder else torch.arange(K, device=H.device) H = H[perm][:, perm] Hinv = torch.cholesky_inverse(torch.linalg.cholesky(H)) Hinv = torch.linalg.cholesky(Hinv, upper=True) group_of = perm // G # original group of each processed column codes = torch.empty_like(W) scales = torch.empty(W.shape[0], K // G, device=W.device) for n0 in range(0, W.shape[0], CHUNK): Wc = W[n0:n0 + CHUNK].clone() Wc[:, dead] = 0 if actorder: Wg = Wc.view(Wc.shape[0], -1, G) scales[n0:n0 + CHUNK] = mse_scale(Wg) if mse else scale_of(Wg, 7) Wc = Wc[:, perm] Q = torch.empty_like(Wc) for i0 in range(0, K, G): i1 = i0 + G W1, Hi = Wc[:, i0:i1].clone(), Hinv[i0:i1, i0:i1] E1 = torch.zeros_like(W1) if not actorder: s_blk = mse_scale(W1[:, None, :])[:, 0] if mse else scale_of(W1, 7) scales[n0:n0 + CHUNK, i0 // G] = s_blk for j in range(G): s = scales[n0:n0 + CHUNK, group_of[i0 + j]] q = torch.clamp(torch.round(W1[:, j] / s), -8, 7) Q[:, i0 + j] = q err = (W1[:, j] - q * s) / Hi[j, j] W1[:, j:] -= err[:, None] * Hi[j, j:][None, :] E1[:, j] = err Wc[:, i1:] -= E1 @ Hinv[i0:i1, i1:] codes[n0:n0 + CHUNK, perm] = Q return codes, scales def deq4(codes, s): return (codes.view(codes.shape[0], -1, G) * s[..., None]).view(codes.shape) def rel(a, b): return ((a - b).norm() / b.norm()).item() def head_errors(codes, s, X): Wq = deq4(codes, s) out, ref = X @ Wq.T, X @ W.T return {"out_err": rel(out, ref), "weight_err": rel(Wq, W), "heldout_top1_agree": (out.argmax(1) == ref.argmax(1)).float().mean().item()} # held-out rows: even ones pick the GPTQ setting, odd ones are reported (not used for the choice) Xsel, Xrep = Xe[0::2], Xe[1::2] manifest = {"K": K, "N": V, "hessian_rows": rows, "heldout_rows": int(Xe.shape[0]), "heldout_stride": EVERY, "heldout_split": "even rows select the GPTQ setting, odd rows are reported", "group_size": G, "sym": True, "column_chunk": CHUNK, "calibration": "quant/calib/calib_256x2048.json (256 x 2048 tokens, EN/DE/tools/code)", "activations": "final-norm output of the INT4-body model (weights dequantized from BODY_DIR)", "grid": {}} t0 = time.time() best = None for damp in [0.001, 0.003, 0.01, 0.03, 0.1]: for actorder in [False, True]: for mse in [False, True]: key = f"damp={damp},actorder={'static' if actorder else 'none'},mse={mse}" codes, s = gptq_int4(W, H, damp, actorder, mse) e = head_errors(codes, s, Xsel)["out_err"] manifest["grid"][key] = e print(f" {key}: select out_err {e:.4%} ({time.time() - t0:.0f} s)", flush=True) if best is None or e < best[0]: best = (e, key, codes, s) manifest["gptq_setting"] = best[1] results = {"gptq": best[2:], "rtn": rtn_int4(W)} for name, (codes, s) in results.items(): manifest[f"head_{name}"] = head_errors(codes, s, Xrep) packed = pack_to_int32(codes.to(torch.int8).cpu(), 4, packed_dim=1) assert torch.equal(unpack_from_int32(packed, 4, codes.shape, packed_dim=1), codes.to(torch.int8).cpu()) save_file({"lm_head.weight_packed": packed, "lm_head.weight_scale": s.to(torch.bfloat16).cpu().contiguous(), "lm_head.weight_shape": torch.tensor([V, K], dtype=torch.int64)}, f"{out_dir}/head_{name}.safetensors") print(f"head {name}: {manifest[f'head_{name}']} ({time.time() - t0:.0f} s)", flush=True) # --- INT8 embedding, per-row scale s8 = scale_of(W, 127) c8 = torch.clamp(torch.round(W / s8[:, None]), -128, 127) We = c8 * s8[:, None] tok_ids = torch.cat([s[0] for s in samples])[::EVERY][:EVAL_CAP].to(dev) # embedding rows as looked up manifest["embed_int8"] = {"weight_err": rel(We, W), "lookup_err_heldout_tokens": rel(We[tok_ids], W[tok_ids]), "scheme": "per-row absmax/127, BF16 scales, codes from the rounded scale"} packed8 = pack_to_int32(c8.to(torch.int8).cpu(), 8, packed_dim=1) assert torch.equal(unpack_from_int32(packed8, 8, c8.shape, packed_dim=1), c8.to(torch.int8).cpu()) save_file({"model.embed_tokens.weight_packed": packed8, "model.embed_tokens.weight_scale": s8[:, None].to(torch.bfloat16).cpu().contiguous(), "model.embed_tokens.weight_shape": torch.tensor([V, K], dtype=torch.int64)}, f"{out_dir}/embed_int8.safetensors") print(f"embed int8: {manifest['embed_int8']}", flush=True) json.dump(manifest, open(f"{out_dir}/bake_manifest.json", "w"), indent=1)