File size: 10,249 Bytes
e8eb104 | 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 173 174 175 176 177 178 179 180 181 182 183 184 185 | #!/usr/bin/env python3
"""GPTQ INT4 body quantization of a BF16 Qwen3.8-27B (qwen3_5) checkpoint with GPTQModel 7.3.2 on XPU.
python quant_body.py --src /src --dst /dst --calib /calib --nsamples 512 --seqlen 2048 [--layers N]
Body linears -> GPTQ INT4 sym g128, desc_act off, act_group_aware, damp 0.05 (mikeinnyc/SergiioB
layout). GPTQModel's qwen3_5 definition already leaves in_proj_a/in_proj_b, the vision tower and
mtp.* untouched; lm_head=False keeps the head dense BF16, so the result is the greglechin-style
body that research/hybrid-bake/make_dense_from_gptq.py expects.
Calibration (seed 608), disjoint from every eval set (wikitext-2 TEST, HumanEval/MBPP, etc.):
40 % C4 en validation shard 0 - concatenated 2048-token windows
40 % codeparrot-clean-valid - concatenated 2048-token windows of real source files
20 % ultrachat_200k test_sft - whole conversations through the chat template, cut at seqlen
With --tools FILE (hermes-function-calling-v1 func-calling.json) the mix becomes 30 % C4, 40 % code,
10 % ultrachat, 20 % tool-call conversations (half with parallel calls) rendered through the model's
own template with tools= (calib_tools.py), each cut to a window that holds its first assistant turn.
Added 2026-11-02 after BFCL parallel lost 25/100 items: the first calibration set had no tool calls.
The exact token ids are written to <dst>/calib-body.jsonl (+ sha256 in quant-meta.json) so the
run can be reproduced bit-for-bit on the inputs side.
--layers N is the smoke test: a symlinked copy of src whose config keeps only the first N decoder
layers, to check loading, the XPU path and peak host RSS before the multi-hour full run.
"""
import argparse, ctypes, glob, gzip, hashlib, json, os, random, resource, shutil, sys, threading, time
ap = argparse.ArgumentParser()
ap.add_argument("--src", required=True); ap.add_argument("--dst", required=True)
ap.add_argument("--calib", required=True, help="dir with c4/, codeparrot/, ultrachat/")
ap.add_argument("--nsamples", type=int, default=512); ap.add_argument("--seqlen", type=int, default=2048)
ap.add_argument("--layers", type=int, default=0, help="smoke test: keep only the first N decoder layers")
ap.add_argument("--tools", default="", help="hermes func-calling.json: add a 20 %% tool-call slice")
ap.add_argument("--damp", type=float, default=0.05)
ap.add_argument("--offload", default="/dst/.offload")
ap.add_argument("--sync-finalize", action="store_true",
help="drain each layer's pack/offload finalizers before the next layer (bounds host RAM)")
ap.add_argument("--calib-device", default="", help="keep cached calibration activations here (e.g. xpu:0) instead of host RAM")
ap.add_argument("--malloc-trim", action="store_true",
help="call glibc malloc_trim(0) every 20 s (run with MALLOC_ARENA_MAX=2): returns freed heap "
"pages that GPTQModel's worker-thread arenas otherwise keep, which grew host RAM per layer")
a = ap.parse_args()
random.seed(608)
os.makedirs(a.dst, exist_ok=True)
T0 = time.time()
def mem_logger():
while True:
peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6
cur = next(int(l.split()[1]) for l in open("/proc/self/status") if l.startswith("VmRSS")) / 1e6
avail = next(int(l.split()[1]) for l in open("/proc/meminfo") if l.startswith("MemAvailable")) / 1e6
off = sum(os.path.getsize(os.path.join(r, f)) for r, _, fs in os.walk(a.offload) for f in fs) / 1e9 if os.path.isdir(a.offload) else 0
print(f"[mem] t={time.time()-T0:6.0f}s rss={cur:5.1f} peak={peak:5.1f} GB host_avail={avail:5.1f} GB offload_disk={off:5.1f} GB", flush=True)
if a.malloc_trim:
ctypes.CDLL("libc.so.6").malloc_trim(0)
time.sleep(20)
threading.Thread(target=mem_logger, daemon=True).start()
def tensor_census():
# debug (QB_CENSUS=1): every 60 s, the largest groups of live CPU tensors by (shape, dtype)
import gc, collections, torch
while True:
time.sleep(60)
groups = collections.Counter(); seen = set()
for o in gc.get_objects():
try:
if torch.is_tensor(o) and o.device.type == "cpu" and o.numel() > 1_000_000:
st = o.untyped_storage(); key = st.data_ptr()
if key in seen:
continue
seen.add(key); groups[(tuple(o.shape), str(o.dtype))] += st.nbytes()
except Exception:
pass
top = ", ".join(f"{s}{d.replace('torch.', '')}={b / 1e9:.2f}GB" for (s, d), b in groups.most_common(6))
print(f"[census] t={time.time()-T0:6.0f}s total={sum(groups.values()) / 1e9:.1f}GB {top}", flush=True)
if os.environ.get("QB_CENSUS") == "1":
threading.Thread(target=tensor_census, daemon=True).start()
src = a.src
if a.layers:
src = "/tmp/smoke-src"
shutil.rmtree(src, ignore_errors=True); os.makedirs(src)
for fn in os.listdir(a.src):
if fn != "config.json":
os.symlink(os.path.join(a.src, fn), os.path.join(src, fn))
cfg = json.load(open(os.path.join(a.src, "config.json")))
tc = cfg.get("text_config", cfg)
tc["num_hidden_layers"] = a.layers
if "layer_types" in tc:
tc["layer_types"] = tc["layer_types"][:a.layers]
json.dump(cfg, open(os.path.join(src, "config.json"), "w"), indent=2)
print(f"smoke test: {a.layers} layers via {src}", flush=True)
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained(src)
def windows(texts, n):
out, buf = [], []
for t in texts:
buf += tok(t, add_special_tokens=False)["input_ids"] + [tok.eos_token_id]
while len(buf) >= a.seqlen and len(out) < n:
out.append(buf[:a.seqlen]); buf = buf[a.seqlen:]
if len(out) >= n:
break
return out
n_tools = int(a.nsamples * 0.2) if a.tools else 0
n_c4, n_code = int(a.nsamples * (0.3 if a.tools else 0.4)), int(a.nsamples * 0.4)
n_chat = a.nsamples - n_c4 - n_code - n_tools
c4 = [json.loads(l)["text"] for l in gzip.open(glob.glob(f"{a.calib}/c4/**/*.json.gz", recursive=True)[0], "rt")]
random.shuffle(c4)
code = [json.loads(l)["content"] for l in gzip.open(glob.glob(f"{a.calib}/codeparrot/*.json.gz")[0], "rt")]
code = code[:int(len(code) * 0.9)] # last 10 % (file order) is the ppl-code / kld eval set
random.shuffle(code)
import pandas as pd
uc = pd.read_parquet(sorted(glob.glob(f"{a.calib}/ultrachat/**/test_sft*.parquet", recursive=True))[0])
uc = uc.sample(frac=1.0, random_state=608)
samples = windows(c4, n_c4) + windows(code, n_code)
if a.tools:
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import calib_tools
conv = calib_tools.render(tok, a.tools)
random.Random(608).shuffle(conv)
par = [c for c in conv if "</tool_call>\n<tool_call>" in c][:n_tools // 2]
single = [c for c in conv if "</tool_call>\n<tool_call>" not in c and "<tool_call>" in c][:n_tools - len(par)]
end_tok = tok.convert_tokens_to_ids("<|im_end|>")
for c in par + single:
ids = tok(c, add_special_tokens=False)["input_ids"]
# end of the first assistant turn that calls a tool: keep it, plus what follows, inside the window
k = c.find("<tool_call>"); e = len(tok(c[:k], add_special_tokens=False)["input_ids"])
e = next((i for i in range(e, len(ids)) if ids[i] == end_tok), len(ids) - 1) + 1
lo = 0 if e + 64 <= a.seqlen else max(0, min(e + 64, len(ids)) - a.seqlen)
samples.append(list(ids[lo:lo + a.seqlen]))
assert len(samples) == n_c4 + n_code + n_tools, "tool slice short"
for _, r in uc.iterrows():
if len(samples) >= a.nsamples:
break
msgs = [{"role": m["role"], "content": m["content"]} for m in r["messages"]]
# render to text, then tokenize: apply_chat_template(tokenize=True) returns a BatchEncoding in transformers 5
ids = tok(tok.apply_chat_template(msgs, tokenize=False), add_special_tokens=False)["input_ids"]
if len(ids) >= 256:
samples.append(list(ids[:a.seqlen]))
assert len(samples) == a.nsamples, f"built {len(samples)} calibration samples, wanted {a.nsamples}"
with open(os.path.join(a.dst, "calib-body.jsonl"), "w") as f:
for s in samples:
f.write(json.dumps(s) + "\n")
calib_sha = hashlib.sha256(open(os.path.join(a.dst, "calib-body.jsonl"), "rb").read()).hexdigest()
print(f"calibration: {len(samples)} samples (c4 {n_c4}, code {n_code}, chat {n_chat}, tools {n_tools}), "
f"{sum(map(len, samples))} tokens, sha256 {calib_sha[:16]}", flush=True)
calib = [{"input_ids": s, "attention_mask": [1] * len(s)} for s in samples]
from gptqmodel import GPTQModel, QuantizeConfig
import gptqmodel, torch
qcfg = QuantizeConfig(bits=4, group_size=128, sym=True, desc_act=False, act_group_aware=True,
damp_percent=a.damp, true_sequential=True, lm_head=False,
offload_to_disk=True, offload_to_disk_path=a.offload,
wait_for_submodule_finalizers=a.sync_finalize,
**({"calibration_data_device": a.calib_device} if a.calib_device else {}))
print("QuantizeConfig:", qcfg, flush=True)
model = GPTQModel.load(src, qcfg, device="xpu:0")
t = time.time()
model.quantize(calib, batch_size=1, tokenizer=tok)
quant_s = time.time() - t
model.save(a.dst)
shutil.rmtree(a.offload, ignore_errors=True)
meta = {"src": a.src, "layers": a.layers or "all", "nsamples": a.nsamples, "seqlen": a.seqlen,
"mix": {"c4": n_c4, "code": n_code, "chat": n_chat, "tools": n_tools}, "tools_src": "NousResearch/hermes-function-calling-v1@dae3e1d func-calling.json" if a.tools else None, "seed": 608, "damp_percent": a.damp,
"calib_sha256": calib_sha, "calib_device": a.calib_device or "default", "sync_finalize": a.sync_finalize, "malloc_trim": a.malloc_trim, "malloc_arena_max": os.environ.get("MALLOC_ARENA_MAX"), "gptqmodel": gptqmodel.__version__, "torch": torch.__version__,
"quantize_seconds": round(quant_s), "total_seconds": round(time.time() - T0),
"peak_rss_gb": round(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6, 2)}
json.dump(meta, open(os.path.join(a.dst, "quant-meta.json"), "w"), indent=2)
print("DONE", json.dumps(meta), flush=True)
|