Files
xpu-llm-ports/lfm3/quant/gptq_baked/assemble.py
T
Pascal LinxweilerandClaude Opus 5.5 38b0e9a345 lfm3: round 6 - GPTQ INT4 baked (INT4 lm_head + INT8 embedding)
- quant/gptq_baked/: llm-compressor GPTQ W4A16 body (sequential pipeline, verified
  equal to the plain forward), B65-style GPTQ INT4 lm_head bake with a small
  damp/act-order/clipping grid, INT8 per-row embedding, assembly into one
  compressed-tensors checkpoint (1.155 GB vs 3.46 GB BF16)
- plugin: pass quant_config to the token embedding so vLLM's compressed-tensors
  INT8 embedding path is used; BF16/FP8 greedy output unchanged
- tests: INT8 embedding kernel check, quant method dump, head timing, round-6 driver
- NOTES: round 6 results (PPL +8.1%, decode 217 t/s = FP8 pc +14%, head bake
  gives no measurable decode gain on this stack), llama-swap snippet (not applied)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 14:48:48 +01:00

73 lines
3.6 KiB
Python

#!/usr/bin/env python3
"""Assemble an LFM3 checkpoint from the GPTQ INT4 body (quantize_body.py) and the baked tensors
(bake_head_embed.py). The result is one model.safetensors + compressed-tensors quantization_config:
--head gptq|rtn untie: write lm_head.* (INT4, group 128, same scheme as the body) as its own
tensors, tie_word_embeddings=false, config group "lm_head"
--head none keep the tied BF16 head (body-only variant)
--embed int8 replace model.embed_tokens.weight by INT8 + per-row scales, config group for it
Non-weight files (tokenizer, chat template, generation_config, LICENSE, Liquid's code) come from the
original model folder, so the result serves like the original.
python3 assemble.py SRC_MODEL BODY_DIR BAKE_DIR OUT_DIR --head gptq --embed int8
"""
import argparse, copy, glob, json, os, shutil
from safetensors import safe_open
from safetensors.torch import load_file, save_file
ap = argparse.ArgumentParser()
ap.add_argument("src"); ap.add_argument("body"); ap.add_argument("bake"); ap.add_argument("out")
ap.add_argument("--head", choices=["gptq", "rtn", "none"], required=True)
ap.add_argument("--embed", choices=["int8", "none"], required=True)
a = ap.parse_args()
if os.path.exists(a.out) and os.listdir(a.out):
raise SystemExit(f"{a.out} exists and is not empty")
os.makedirs(a.out, exist_ok=True)
tensors = {}
for f in sorted(glob.glob(f"{a.body}/*.safetensors")):
tensors.update(load_file(f))
assert "lm_head.weight" not in tensors, "body checkpoint is expected tied (no lm_head.weight)"
cfg = json.load(open(f"{a.body}/config.json"))
qc = cfg["quantization_config"]
body_group = next(g for g in qc["config_groups"].values() if "Linear" in g["targets"])
if a.head != "none":
tensors.update(load_file(f"{a.bake}/head_{a.head}.safetensors"))
cfg["tie_word_embeddings"] = False
qc["ignore"] = [x for x in qc["ignore"] if x != "lm_head"]
head_group = copy.deepcopy(body_group)
head_group["targets"] = ["lm_head"]
qc["config_groups"]["lm_head"] = head_group
if a.embed == "int8":
del tensors["model.embed_tokens.weight"]
tensors.update(load_file(f"{a.bake}/embed_int8.safetensors"))
emb_group = copy.deepcopy(body_group)
emb_group["targets"] = ["model.embed_tokens"]
emb_group["weights"].update({"num_bits": 8, "strategy": "channel", "group_size": None,
"block_structure": None, "actorder": None})
qc["config_groups"]["embed_tokens"] = emb_group
if a.head == "none":
raise SystemExit("INT8 embedding needs an untied head (the tied head would read the INT8 codes)")
save_file(tensors, f"{a.out}/model.safetensors", metadata={"format": "pt"})
json.dump(cfg, open(f"{a.out}/config.json", "w"), indent=2)
skip = {"config.json", "model.safetensors", "README.md", ".gitattributes"}
for f in os.listdir(a.src):
p = f"{a.src}/{f}"
if os.path.isfile(p) and f not in skip and not f.endswith(".safetensors"):
shutil.copy2(p, f"{a.out}/{f}")
for f in ["quant_run.json"]:
shutil.copy2(f"{a.body}/{f}", f"{a.out}/{f}")
manifest = json.load(open(f"{a.bake}/bake_manifest.json"))
bake = {"head": a.head, "embed": a.embed, "body": json.load(open(f"{a.body}/quant_run.json")),
"bake": {k: v for k, v in manifest.items() if not k.startswith("head_") or k == f"head_{a.head}"}}
if a.embed == "none":
bake["bake"].pop("embed_int8", None)
json.dump(bake, open(f"{a.out}/BAKE.json", "w"), indent=1)
with safe_open(f"{a.out}/model.safetensors", "pt") as sf:
n = len(list(sf.keys()))
size = os.path.getsize(f"{a.out}/model.safetensors")
print(f"{a.out}: {n} tensors, model.safetensors {size / 1e9:.3f} GB, head={a.head} embed={a.embed}")