lfm3: add INT4, FP8 per-channel and VL notes, tests, eval and results
Sync the repo with the working directory: full NOTES.md (rounds 4-5, LFM3-VL), VL tests and test images, quality eval, AutoRound W4A16 quantization scripts and calibration recipe, the variant.sh MODEL/DOCKER_ENV options, and the remaining benchmark results. Large regenerable artifacts (INT4 checkpoint, ref_vl.pt, raw logprob dumps) stay out. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0412bb1f72
commit
1834792bb8
67 files changed
+119589
-9
No files matched your search
@@ -0,0 +1,74 @@
|
||||
#!/usr/bin/env python3
|
||||
"""AutoRound W4A16 (bits 4, group 128, sym) for LFM3-1.7B with Liquid's remote code, exported in
|
||||
AutoRound's native format (vLLM: quant_method auto-round -> INC). Only the nn.Linear layers of the
|
||||
24 decoder blocks are quantized; self_attn.gate_proj (16-output gate, BF16 in our vLLM plugin) is
|
||||
kept at 16 bit. Embedding / tied lm_head, norms and the conv kernels are not Linear-in-block or are
|
||||
excluded by AutoRound's defaults.
|
||||
|
||||
python3 quantize_autoround.py MODEL_DIR CALIB.pt OUT_DIR [DEVICE=xpu] [ITERS=200]
|
||||
"""
|
||||
import json, sys, time
|
||||
import torch
|
||||
from auto_round import AutoRound
|
||||
from transformers import AutoModelForCausalLM, AutoTokenizer
|
||||
|
||||
model_dir, calib, out_dir = sys.argv[1:4]
|
||||
device = sys.argv[4] if len(sys.argv) > 4 else "xpu"
|
||||
iters = int(sys.argv[5]) if len(sys.argv) > 5 else 200
|
||||
|
||||
tok = AutoTokenizer.from_pretrained(model_dir)
|
||||
model = AutoModelForCausalLM.from_pretrained(model_dir, dtype=torch.bfloat16, trust_remote_code=True)
|
||||
samples = torch.load(calib)
|
||||
|
||||
# AutoRound records the kwargs that reach block 0 (a conv layer) and replays them to every block, but
|
||||
# LFM3 hands each layer the RoPE table and mask of its own type (conv / sliding / full). Rebuild both
|
||||
# inside each layer from its type, with Liquid's own helpers, so attention blocks see the right RoPE
|
||||
# and sliding layers the 256-token window.
|
||||
inner = model.model
|
||||
hf_mod = sys.modules[type(inner).__module__]
|
||||
layer_cls = type(inner.layers[0])
|
||||
orig_forward = layer_cls.forward
|
||||
for i, layer in enumerate(inner.layers):
|
||||
layer._lfm3_type = model.config.layer_types[i]
|
||||
_ctx_cache = {}
|
||||
|
||||
|
||||
def _layer_ctx(hidden_states, position_ids):
|
||||
key = (hidden_states.shape[0], hidden_states.shape[1], hidden_states.device, hidden_states.dtype)
|
||||
if key not in _ctx_cache:
|
||||
if position_ids is None:
|
||||
position_ids = torch.arange(hidden_states.shape[1], device=hidden_states.device)[None]
|
||||
masks = hf_mod.create_masks_by_layer_type(model.config, hidden_states, None, None, position_ids)
|
||||
pe = {t: inner.rotary_emb(hidden_states, position_ids=position_ids, layer_type=t)
|
||||
for t in inner.rotary_emb.layer_types}
|
||||
_ctx_cache[key] = (position_ids, masks, pe)
|
||||
return _ctx_cache[key]
|
||||
|
||||
|
||||
def per_type_forward(self, hidden_states, position_embeddings=None, attention_mask=None,
|
||||
position_ids=None, past_key_values=None, seq_idx=None, **kwargs):
|
||||
position_ids, masks, pe = _layer_ctx(hidden_states, position_ids)
|
||||
return orig_forward(self, hidden_states, position_embeddings=pe.get(self._lfm3_type),
|
||||
attention_mask=masks[self._lfm3_type], position_ids=position_ids,
|
||||
past_key_values=None, seq_idx=None, **kwargs)
|
||||
|
||||
|
||||
layer_cls.forward = per_type_forward
|
||||
|
||||
linears = [n for n, m in model.named_modules() if isinstance(m, torch.nn.Linear)]
|
||||
keep16 = {n: {"bits": 16} for n in linears if n.endswith("self_attn.gate_proj")}
|
||||
to_quant = [n for n in linears if n.startswith("model.layers.") and n not in keep16]
|
||||
print(f"{len(linears)} nn.Linear total; quantizing {len(to_quant)}; keeping 16-bit: "
|
||||
f"{len(keep16)} gate_proj + {[n for n in linears if not n.startswith('model.layers.')]}", flush=True)
|
||||
|
||||
t0 = time.time()
|
||||
ar = AutoRound(model, tok, bits=4, group_size=128, sym=True, dataset=samples, nsamples=len(samples),
|
||||
seqlen=samples[0].shape[-1], iters=iters, layer_config=keep16, device_map=device,
|
||||
enable_torch_compile=False)
|
||||
ar.quantize_and_save(out_dir, format="auto_round")
|
||||
dt = time.time() - t0
|
||||
json.dump({"tool": "auto-round", "bits": 4, "group_size": 128, "sym": True, "iters": iters,
|
||||
"nsamples": len(samples), "seqlen": int(samples[0].shape[-1]), "device": device,
|
||||
"seconds": round(dt), "kept_16bit": sorted(keep16), "quantized_linears": len(to_quant)},
|
||||
open(f"{out_dir}/quant_run.json", "w"), indent=1)
|
||||
print(f"done in {dt/60:.1f} min -> {out_dir}")
|
||||
Reference in new issue
Block a user