"""Requantize thinkingmachines/Inkling-2-Mini into the SM86-Fast checkpoint. usage: quantize_fast.py SRC HESSIANS OUT [--layers 0-23] [--device cuda:0] [--batch 16] [--no-attn] [--keep-visual] [--prior 64] [--damp 0.01] [--draft DRAFT_HESSIANS] [--draft-only] [--lora ADAPTER] - Routed experts (report B1): the official NVFP4 / MXFP8 weights are dequantized exactly (as transformers' Inkling2LoopDequantizeExperts) and quantized by symmetric GPTQ (uint4b8, g128, positive scales) on the per-expert Hessians the serving engine collected from the official model (routing-weighted rows, accumulated over the three loop passes). Rarely routed experts are shrunk toward the layer's pooled Hessian (`--prior` pseudo-rows). - Attention projections (B2, unless --no-attn): the same quantizer on the full-space input Hessians (qkvr inputs are replicated over TP ranks; wo's are gathered), so the codes do not depend on the serving TP size. - DSpark draft (A2, with --draft): its attention and MLP projections by the same quantizer on Hessians collected while the official model drafted (row-parallel inputs gathered); markov_head, norms and fuse weights stay BF16, and mtp_config.int4_projections marks the format. Without --draft, mtp.safetensors is copied as is. - With --lora, a PEFT LoRA adapter on attention projections (e.g. the OpenUncensored wo_ud refusal-removal adapter) is merged into the BF16 weights, W + (alpha / r) B A in fp32, before they are quantized. - model.visual.* is dropped unless --keep-visual; everything else is copied as is. Writes compressed-tensors pack-quantized tensors and a config.json declaring them. """ import json import os import re import shutil import sys import time import torch from safetensors import safe_open from safetensors.torch import save_file sys.path.insert(0, os.path.expanduser("~/dev/model-loader/backends/vllm-inkling2/vllm-src")) from vllm.models.inkling2.nvidia.ops import gptq # noqa: E402 src, hdir, out = sys.argv[1:4] arg = lambda k, d: type(d)(sys.argv[sys.argv.index(k) + 1]) if k in sys.argv else d spec = arg("--layers", "0-23") layers = sorted({i for p in spec.split(",") for i in range(int(p.split("-")[0]), int(p.split("-")[-1]) + 1)}) device = torch.device(arg("--device", "cuda:0")) batch = arg("--batch", 16) prior = arg("--prior", 64.0) damp = arg("--damp", 0.01) do_attn = "--no-attn" not in sys.argv draft_dir = arg("--draft", "") draft_only = "--draft-only" in sys.argv DRAFT_INPUT = {"q_proj": "qkv_proj.x", "k_proj": "qkv_proj.x", "v_proj": "qkv_proj.x", "k_proj_ctx": "kv_proj_ctx.x", "v_proj_ctx": "kv_proj_ctx.x", "o_proj": "o_proj.full", "gate_proj": "gate_up_proj.x", "up_proj": "gate_up_proj.x", "down_proj": "down_proj.full"} keep_visual = "--keep-visual" in sys.argv lora_dir = arg("--lora", "") GROUP = 128 E2M1 = torch.tensor([0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0]) ATTN_INPUT = {"wq_du": "q", "wr_du": "q", "gate_attn": "q", "attn_sink_proj": "q", "wk_dv": "k", "wv_dv": "v"} attn_name = re.compile(r"\.attn\.(" + "|".join((*ATTN_INPUT, "wo_ud")) + r")\.weight$") os.makedirs(out, exist_ok=True) f = safe_open(os.path.join(src, "model-00001-of-00001.safetensors"), "pt", device="cpu") keys = list(f.keys()) stats: dict = {"experts": {}, "attn": {}} lora: dict[str, torch.Tensor] = {} if lora_dir: from safetensors.torch import load_file lora_cfg = json.load(open(os.path.join(lora_dir, "adapter_config.json"))) assert not lora_cfg.get("use_rslora") and not lora_cfg.get("use_dora"), lora_cfg scaling = lora_cfg["lora_alpha"] / lora_cfg["r"] adapter = load_file(os.path.join(lora_dir, "adapter_model.safetensors")) for k in adapter: if k.endswith(".lora_A.weight"): target = k.removeprefix("base_model.model.").removesuffix(".lora_A.weight") b = adapter[k.replace(".lora_A.", ".lora_B.")].float() lora[target + ".weight"] = scaling * (b @ adapter[k].float()) assert all(attn_name.search(k) for k in lora), sorted(lora) stats["lora"] = {"adapter": lora_dir, "scaling": scaling, "targets": sorted(lora)} def dequant_experts(prefix: str, proj: str, experts: slice) -> torch.Tensor: """fp32 `[e, N, K]` official expert weights (NVFP4 or MXFP8).""" w = f.get_slice(f"{prefix}.{proj}_weight")[experts].to(device) scale = f.get_slice(f"{prefix}.{proj}_weight_scale")[experts].to(device) amax_key = f"{prefix}.{proj}_weight_amax" e, n = w.shape[:2] if amax_key in keys: # NVFP4: e2m1 pairs (even element low), e4m3 per 16, amax / denominator lut = E2M1.to(device) codes = w.long() vals = torch.stack((lut[codes & 0xF], lut[codes >> 4]), dim=-1).view(e, n, -1, 16) factor = f.get_tensor(amax_key)[experts].to(device).float() / f.get_tensor( f"{prefix}.{proj}_weight_outer_scale_denominator").to(device).float() vals = vals * scale.float().unsqueeze(-1) * factor.view(e, 1, 1, 1) else: # MXFP8: e4m3 values, ue8m0 per 32 assert scale.dtype == torch.uint8 vals = w.float().view(e, n, -1, 32) * torch.exp2(scale.float() - 127).unsqueeze(-1) return vals.reshape(e, n, -1) def load_rank(name: str, rank: int) -> dict: return torch.load(os.path.join(hdir, f"rank{rank}", name + ".pt"), map_location="cpu") def expert_hessians(name: str, num: int) -> tuple[torch.Tensor, torch.Tensor]: """Per-expert mean Hessians `[E, K, K]` (both ranks' experts) and row counts.""" parts = sorted((load_rank(name, r) for r in (0, 1)), key=lambda s: s["expert_start"]) h = torch.cat([p["h"] for p in parts]) n = torch.cat([p["n"] for p in parts]).double() assert h.shape[0] == num and torch.isfinite(h).all(), name pooled = h.double().sum(0) / n.sum() mean = (h.double() + prior * pooled) / (n + prior).view(-1, 1, 1) return mean.float(), n def pack_ct(codes: torch.Tensor, scales: torch.Tensor, name: str, tensors: dict) -> None: """compressed-tensors pack-quantized symmetric int4: unsigned codes (q + 8), eight per int32 along K, first column in the low bits.""" n, k = codes.shape words = codes.view(n, k // 8, 8).to(torch.int32) shifts = torch.arange(0, 32, 4, dtype=torch.int32, device=codes.device) tensors[f"{name}.weight_packed"] = (words << shifts).sum(-1, dtype=torch.int32).cpu() tensors[f"{name}.weight_scale"] = scales.to(torch.bfloat16).cpu() tensors[f"{name}.weight_shape"] = torch.tensor([n, k], dtype=torch.int64) def rel_err(w: torch.Tensor, codes: torch.Tensor, scales: torch.Tensor, h: torch.Tensor) -> torch.Tensor: """Output-error energy of the quantized weight relative to the weight's, per matrix.""" d = gptq.dequantize_w4_sym(codes, scales) - w num = torch.einsum("bnk,bkl,bnl->b", d, h, d) den = torch.einsum("bnk,bkl,bnl->b", w, h, w) return num / den def quantize_layer_experts(layer: int, tensors: dict) -> None: prefix = f"model.llm.layers.{layer}.mlp.experts" num = f.get_slice(f"{prefix}.w13_weight").get_shape()[0] for proj in ("w13", "w2"): h_all, n_rows = expert_hessians(f"model.layers.{layer}.experts.{proj}", num) errs = [] for start in range(0, num, batch): sl = slice(start, min(start + batch, num)) w = dequant_experts(prefix, proj, sl) h = h_all[sl].to(device) codes, scales = gptq.gptq_w4_sym(w, h, damp) errs.append(rel_err(w, codes, scales, h).cpu()) for i, e in enumerate(range(sl.start, sl.stop)): base = f"model.llm.layers.{layer}.mlp.experts.{e}" if proj == "w13": pack_ct(codes[i, 0::2], scales[i, 0::2], f"{base}.gate_proj", tensors) pack_ct(codes[i, 1::2], scales[i, 1::2], f"{base}.up_proj", tensors) else: pack_ct(codes[i], scales[i], f"{base}.down_proj", tensors) del w, h, codes, scales err = torch.cat(errs) stats["experts"][f"{layer}.{proj}"] = { "rel_err_mean": err.mean().item(), "rel_err_max": err.max().item(), "rows_min": int(n_rows.min()), "rows_median": int(n_rows.median()), "experts_below_prior": int((n_rows < prior).sum()), } print(f"layer {layer} {proj}: rel err mean {err.mean():.4e} max {err.max():.4e}, rows min " f"{int(n_rows.min())} median {int(n_rows.median())}", flush=True) def attn_hessian(*names: str) -> torch.Tensor: """Mean Hessian over the saved inputs among `names` (rows summed).""" h, n = 0, 0 for name in names: if not os.path.exists(os.path.join(hdir, "rank0", name + ".pt")): continue saved = load_rank(name, 0) assert saved["n"] > 0 and torch.isfinite(saved["h"]).all(), name h, n = h + saved["h"].double(), n + saved["n"] assert n > 0, names return (h / n).float().to(device) def quantize_layer_attn(layer: int, tensors: dict) -> None: base = f"model.llm.layers.{layer}.attn" hprefix = f"model.layers.{layer}.attn" for proj in (*ATTN_INPUT, "wo_ud"): w = f.get_tensor(f"{base}.{proj}.weight").to(device).float() delta = lora.pop(f"{base}.{proj}.weight", None) if delta is not None: w += delta.to(device) if proj == "wo_ud": h = attn_hessian(f"{hprefix}.wo.full") else: # Local layers project one input (`x`); full-attention layers, and # loop passes after the first, project separate q/k/v inputs. h = attn_hessian(f"{hprefix}.qkvr.x", f"{hprefix}.qkvr.{ATTN_INPUT[proj]}") codes, scales = gptq.gptq_w4_sym(w, h, damp) err = rel_err(w[None], codes[None], scales[None], h[None]).item() stats["attn"][f"{layer}.{proj}"] = err pack_ct(codes, scales, f"{base}.{proj}", tensors) print(f"layer {layer} attn: rel err max {max(v for k, v in stats['attn'].items() if k.startswith(f'{layer}.')):.4e}", flush=True) def quantize_draft() -> None: """mtp.safetensors with the draft projections in symmetric int4.""" d = safe_open(os.path.join(src, "mtp.safetensors"), "pt", device="cpu") tensors, errs = {}, {} for k in d.keys(): m = re.fullmatch(r"layers\.(\d+)\.(self_attn|mlp)\.(\w+)\.weight", k) if m is None or m.group(3) not in DRAFT_INPUT: tensors[k] = d.get_tensor(k) continue layer, block, proj = m.groups() suffix = f"layers.{layer}.{block}.{DRAFT_INPUT[proj]}.pt" found = [n for n in os.listdir(os.path.join(draft_dir, "rank0")) if n.endswith(suffix)] assert len(found) == 1, (k, found) saved = torch.load(os.path.join(draft_dir, "rank0", found[0]), map_location="cpu") assert saved["n"] > 0 and torch.isfinite(saved["h"]).all(), k h = (saved["h"] / saved["n"]).to(device) w = d.get_tensor(k).to(device).float() codes, scales = gptq.gptq_w4_sym(w, h, damp) errs[k] = rel_err(w[None], codes[None], scales[None], h[None]).item() pack_ct(codes, scales, k.removesuffix(".weight"), tensors) save_file(tensors, os.path.join(out, "mtp.safetensors"), metadata={"format": "pt"}) stats["draft"] = errs print(f"draft: rel err max {max(errs.values()):.4e} mean {sum(errs.values()) / len(errs):.4e}", flush=True) if draft_only: stats = json.load(open(os.path.join(out, "quantize_stats.json"))) quantize_draft() config = json.load(open(os.path.join(out, "config.json"))) config["mtp_config"]["int4_projections"] = True json.dump(config, open(os.path.join(out, "config.json"), "w"), indent=2) json.dump(stats, open(os.path.join(out, "quantize_stats.json"), "w"), indent=1) sys.exit(0) t0 = time.time() expert_re = re.compile(r"model\.llm\.layers\.(\d+)\.mlp\.experts\.w(13|2)_weight\w*") attn_re = re.compile(r"model\.llm\.layers\.(\d+)\.attn\.(" + "|".join((*ATTN_INPUT, "wo_ud")) + r")\.weight") index: dict[str, str] = {} shard = 0 def flush(tensors: dict) -> None: global shard if not tensors: return shard += 1 fname = f"model-{shard:05d}.safetensors" save_file(tensors, os.path.join(out, fname), metadata={"format": "pt"}) for k in tensors: index[k] = fname tensors.clear() # Non-quantized tensors first (one shard), then one shard per layer. rest = {} for k in keys: if k.startswith("model.visual.") and not keep_visual: continue m = expert_re.fullmatch(k) if m is not None and int(m.group(1)) in layers: continue a = attn_re.fullmatch(k) if a is not None and do_attn and int(a.group(1)) in layers: continue if m is not None: raise SystemExit(f"{k}: layer not requantized (pass every layer)") rest[k] = f.get_tensor(k) flush(rest) for layer in layers: tensors: dict = {} quantize_layer_experts(layer, tensors) if do_attn: quantize_layer_attn(layer, tensors) flush(tensors) torch.cuda.empty_cache() print(f"layer {layer} done at {time.time() - t0:.0f}s", flush=True) assert not lora, f"LoRA targets outside the requantized layers: {sorted(lora)}" total = sum(os.path.getsize(os.path.join(out, v)) for v in set(index.values())) for i, fname in enumerate(sorted(set(index.values())), 1): new = f"model-{i:05d}-of-{shard:05d}.safetensors" os.replace(os.path.join(out, fname), os.path.join(out, new)) index = {k: (new if v == fname else v) for k, v in index.items()} json.dump({"metadata": {"total_size": total}, "weight_map": dict(sorted(index.items()))}, open(os.path.join(out, "model.safetensors.index.json"), "w"), indent=2) weights = {"num_bits": 4, "type": "int", "symmetric": True, "strategy": "group", "group_size": 128, "dynamic": False, "actorder": None, "block_structure": None, "observer": "minmax", "observer_kwargs": {}, "scale_dtype": None, "zp_dtype": None} groups = {"group_0": {"targets": [r"re:.*mlp\.experts\.\d+\.(gate|up|down)_proj$"], "weights": weights, "input_activations": None, "output_activations": None, "format": "pack-quantized"}} if do_attn: groups["group_1"] = {"targets": [r"re:.*attn\.(" + "|".join((*ATTN_INPUT, "wo_ud")) + r")$"], "weights": weights, "input_activations": None, "output_activations": None, "format": "pack-quantized"} config = json.load(open(os.path.join(src, "config.json"))) if draft_dir: config["mtp_config"]["int4_projections"] = True config["quantization_config"] = { "quant_method": "compressed-tensors", "format": "pack-quantized", "quantization_status": "compressed", "config_groups": groups, "ignore": [], "kv_cache_scheme": None, "sparsity_config": {}, "transform_config": {}, "global_compression_ratio": None, "version": "0.19.0"} json.dump(config, open(os.path.join(out, "config.json"), "w"), indent=2) for name in os.listdir(src): if name in ("config.json", "hf_quant_config.json", "model.safetensors.index.json", "REVISION", "README.md") \ or name.startswith("model-") or (draft_dir and name == "mtp.safetensors"): continue if os.path.isdir(os.path.join(src, name)): shutil.copytree(os.path.join(src, name), os.path.join(out, name), dirs_exist_ok=True) else: shutil.copy2(os.path.join(src, name), os.path.join(out, name)) if draft_dir: quantize_draft() json.dump(stats, open(os.path.join(out, "quantize_stats.json"), "w"), indent=1) print(f"FINISHED in {time.time() - t0:.0f}s, {total / 2**30:.2f} GiB", flush=True)