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,105 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build the AutoRound calibration set for LFM3-1.7B: chat-formatted conversations (the model's own
|
||||
chat template, incl. tool calls), shuffled and packed into exactly SEQLEN-token samples (AutoRound
|
||||
drops samples shorter than seqlen). Writes OUT (list of [1, SEQLEN] LongTensors) + a JSON recipe.
|
||||
|
||||
python3 build_calib.py MODEL_DIR OUT.pt [NSAMPLES=256] [SEQLEN=2048]
|
||||
|
||||
Mix by token share: English chat 45% (ultrachat_200k test_sft), German 20% (oasst1, lang=de,
|
||||
prompter->assistant pairs), tool calls 15% (glaive-function-calling-v2, converted to the template's
|
||||
tools / tool_calls), code 20% (python_code_instructions_18k_alpaca).
|
||||
"""
|
||||
import ast, json, random, re, sys
|
||||
import torch
|
||||
from datasets import load_dataset
|
||||
from transformers import AutoTokenizer
|
||||
|
||||
model_dir, out = sys.argv[1], sys.argv[2]
|
||||
NSAMPLES = int(sys.argv[3]) if len(sys.argv) > 3 else 256
|
||||
SEQLEN = int(sys.argv[4]) if len(sys.argv) > 4 else 2048
|
||||
SHARE = {"en_chat": 0.45, "de_chat": 0.20, "tool_call": 0.15, "code": 0.20}
|
||||
rng = random.Random(0)
|
||||
tok = AutoTokenizer.from_pretrained(model_dir)
|
||||
|
||||
|
||||
def render(messages, tools=None):
|
||||
return tok.apply_chat_template(messages, tools=tools, tokenize=False)
|
||||
|
||||
|
||||
def en_chat():
|
||||
for r in load_dataset("HuggingFaceH4/ultrachat_200k", split="test_sft").shuffle(seed=0):
|
||||
yield render([{"role": m["role"], "content": m["content"]} for m in r["messages"]])
|
||||
|
||||
|
||||
def de_chat():
|
||||
ds = load_dataset("OpenAssistant/oasst1", split="train").filter(lambda r: r["lang"] == "de")
|
||||
by_id = {r["message_id"]: r for r in ds}
|
||||
pairs = [(by_id[r["parent_id"]]["text"], r["text"]) for r in ds
|
||||
if r["role"] == "assistant" and r["parent_id"] in by_id]
|
||||
rng.shuffle(pairs)
|
||||
for q, a in pairs:
|
||||
yield render([{"role": "user", "content": q}, {"role": "assistant", "content": a}])
|
||||
|
||||
|
||||
def tool_call():
|
||||
turn = re.compile(r"(USER|ASSISTANT|FUNCTION RESPONSE):\s*(.*?)(?=\n+(?:USER|ASSISTANT|FUNCTION RESPONSE):|\Z)", re.S)
|
||||
for r in load_dataset("glaiveai/glaive-function-calling-v2", split="train").shuffle(seed=0):
|
||||
if "<functioncall>" not in r["chat"]:
|
||||
continue
|
||||
try:
|
||||
specs = r["system"].split("-", 1)[1]
|
||||
tools = [{"type": "function", "function": json.loads(s)}
|
||||
for s in re.findall(r"\{.*?\}\s*(?=\n\s*\{|\Z)", specs.strip(), re.S)]
|
||||
msgs = []
|
||||
for role, text in turn.findall(r["chat"]):
|
||||
text = text.replace("<|endoftext|>", "").strip()
|
||||
if role == "USER":
|
||||
msgs.append({"role": "user", "content": text})
|
||||
elif role == "FUNCTION RESPONSE":
|
||||
msgs.append({"role": "tool", "content": text})
|
||||
elif text.startswith("<functioncall>"):
|
||||
call = text[len("<functioncall>"):].strip()
|
||||
name = re.search(r'"name":\s*"([^"]+)"', call).group(1)
|
||||
args = re.search(r'"arguments":\s*(\'.*\'|\{.*\})', call, re.S).group(1)
|
||||
args = json.loads(ast.literal_eval(args) if args.startswith("'") else args)
|
||||
msgs.append({"role": "assistant", "content": "", "tool_calls": [
|
||||
{"type": "function", "function": {"name": name, "arguments": args}}]})
|
||||
else:
|
||||
msgs.append({"role": "assistant", "content": text})
|
||||
if tools and msgs and msgs[0]["role"] == "user":
|
||||
yield render(msgs, tools)
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
|
||||
def code():
|
||||
for r in load_dataset("iamtarun/python_code_instructions_18k_alpaca", split="train").shuffle(seed=0):
|
||||
q = r["instruction"] + (f"\n\nInput: {r['input']}" if r["input"].strip() else "")
|
||||
yield render([{"role": "user", "content": q}, {"role": "assistant", "content": f"```python\n{r['output']}\n```"}])
|
||||
|
||||
|
||||
# Collect conversations per source until its token budget is met, then shuffle and pack.
|
||||
budget = NSAMPLES * SEQLEN
|
||||
convs, stats = [], {}
|
||||
for name, gen in [("en_chat", en_chat), ("de_chat", de_chat), ("tool_call", tool_call), ("code", code)]:
|
||||
want, got, n = int(budget * SHARE[name]), 0, 0
|
||||
for text in gen():
|
||||
ids = tok(text, add_special_tokens=False)["input_ids"][:SEQLEN]
|
||||
convs.append(ids); got += len(ids); n += 1
|
||||
if got >= want:
|
||||
break
|
||||
stats[name] = {"conversations": n, "tokens": got}
|
||||
print(name, stats[name], flush=True)
|
||||
rng.shuffle(convs)
|
||||
stream = [t for c in convs for t in c]
|
||||
samples = [torch.tensor([stream[i:i + SEQLEN]]) for i in range(0, len(stream) - SEQLEN + 1, SEQLEN)][:NSAMPLES]
|
||||
torch.save(samples, out)
|
||||
recipe = {"nsamples": len(samples), "seqlen": SEQLEN, "share_target": SHARE, "sources": stats,
|
||||
"datasets": {"en_chat": "HuggingFaceH4/ultrachat_200k:test_sft",
|
||||
"de_chat": "OpenAssistant/oasst1:train lang=de (prompter->assistant pairs)",
|
||||
"tool_call": "glaiveai/glaive-function-calling-v2:train (only rows with <functioncall>)",
|
||||
"code": "iamtarun/python_code_instructions_18k_alpaca:train"},
|
||||
"format": "model chat template (tools via tools=, calls via tool_calls), conversations shuffled "
|
||||
"(seed 0) and packed back-to-back into exact SEQLEN-token samples"}
|
||||
json.dump(recipe, open(out.replace(".pt", ".json"), "w"), indent=1)
|
||||
print(f"{len(samples)} samples x {SEQLEN} tokens -> {out}")
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"nsamples": 256,
|
||||
"seqlen": 2048,
|
||||
"share_target": {
|
||||
"en_chat": 0.45,
|
||||
"de_chat": 0.2,
|
||||
"tool_call": 0.15,
|
||||
"code": 0.2
|
||||
},
|
||||
"sources": {
|
||||
"en_chat": {
|
||||
"conversations": 199,
|
||||
"tokens": 237340
|
||||
},
|
||||
"de_chat": {
|
||||
"conversations": 567,
|
||||
"tokens": 105303
|
||||
},
|
||||
"tool_call": {
|
||||
"conversations": 239,
|
||||
"tokens": 78660
|
||||
},
|
||||
"code": {
|
||||
"conversations": 629,
|
||||
"tokens": 106397
|
||||
}
|
||||
},
|
||||
"datasets": {
|
||||
"en_chat": "HuggingFaceH4/ultrachat_200k:test_sft",
|
||||
"de_chat": "OpenAssistant/oasst1:train lang=de (prompter->assistant pairs)",
|
||||
"tool_call": "glaiveai/glaive-function-calling-v2:train (only rows with <functioncall>)",
|
||||
"code": "iamtarun/python_code_instructions_18k_alpaca:train"
|
||||
},
|
||||
"format": "model chat template (tools via tools=, calls via tool_calls), conversations shuffled (seed 0) and packed back-to-back into exact SEQLEN-token samples"
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
# Verify the per-layer-type forward patch in quantize_autoround.py leaves the model's logits unchanged.
|
||||
import runpy, sys, torch
|
||||
sys.argv = ["x", "/model", "/quant/calib/calib_256x2048.pt", "/tmp/unused"]
|
||||
src = open("/quant/quantize_autoround.py").read().split("t0 = time.time()")[0] # setup + patch, no quantization
|
||||
g = {"__name__": "check"}
|
||||
from transformers import AutoModelForCausalLM
|
||||
ref = AutoModelForCausalLM.from_pretrained("/model", dtype=torch.bfloat16, trust_remote_code=True).to("xpu").eval()
|
||||
x = torch.load("/quant/calib/calib_256x2048.pt")[3][:, :1000].to("xpu")
|
||||
with torch.no_grad():
|
||||
a = ref(x).logits.float()
|
||||
del ref
|
||||
exec(src, g)
|
||||
m = g["model"].to("xpu").eval()
|
||||
with torch.no_grad():
|
||||
b = m(x).logits.float()
|
||||
print("max |dlogit|", (a - b).abs().max().item(), "top1 agree", (a.argmax(-1) == b.argmax(-1)).float().mean().item())
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"tool": "auto-round",
|
||||
"bits": 4,
|
||||
"group_size": 128,
|
||||
"sym": true,
|
||||
"iters": 200,
|
||||
"nsamples": 256,
|
||||
"seqlen": 2048,
|
||||
"device": "xpu",
|
||||
"seconds": 988,
|
||||
"kept_16bit": [
|
||||
"model.layers.10.self_attn.gate_proj",
|
||||
"model.layers.12.self_attn.gate_proj",
|
||||
"model.layers.14.self_attn.gate_proj",
|
||||
"model.layers.16.self_attn.gate_proj",
|
||||
"model.layers.18.self_attn.gate_proj",
|
||||
"model.layers.2.self_attn.gate_proj",
|
||||
"model.layers.20.self_attn.gate_proj",
|
||||
"model.layers.22.self_attn.gate_proj",
|
||||
"model.layers.4.self_attn.gate_proj",
|
||||
"model.layers.6.self_attn.gate_proj",
|
||||
"model.layers.8.self_attn.gate_proj"
|
||||
],
|
||||
"quantized_linears": 142
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
{
|
||||
"bits": 4,
|
||||
"data_type": "int",
|
||||
"group_size": 128,
|
||||
"sym": true,
|
||||
"autoround_version": "0.16.1",
|
||||
"block_name_to_quantize": "model.layers",
|
||||
"quant_method": "auto-round",
|
||||
"packing_format": "auto_round:auto_gptq",
|
||||
"extra_config": {
|
||||
"model.layers.2.self_attn.gate_proj": {
|
||||
"bits": 16,
|
||||
"data_type": "fp"
|
||||
},
|
||||
"model.layers.4.self_attn.gate_proj": {
|
||||
"bits": 16,
|
||||
"data_type": "fp"
|
||||
},
|
||||
"model.layers.6.self_attn.gate_proj": {
|
||||
"bits": 16,
|
||||
"data_type": "fp"
|
||||
},
|
||||
"model.layers.8.self_attn.gate_proj": {
|
||||
"bits": 16,
|
||||
"data_type": "fp"
|
||||
},
|
||||
"model.layers.10.self_attn.gate_proj": {
|
||||
"bits": 16,
|
||||
"data_type": "fp"
|
||||
},
|
||||
"model.layers.12.self_attn.gate_proj": {
|
||||
"bits": 16,
|
||||
"data_type": "fp"
|
||||
},
|
||||
"model.layers.14.self_attn.gate_proj": {
|
||||
"bits": 16,
|
||||
"data_type": "fp"
|
||||
},
|
||||
"model.layers.16.self_attn.gate_proj": {
|
||||
"bits": 16,
|
||||
"data_type": "fp"
|
||||
},
|
||||
"model.layers.18.self_attn.gate_proj": {
|
||||
"bits": 16,
|
||||
"data_type": "fp"
|
||||
},
|
||||
"model.layers.20.self_attn.gate_proj": {
|
||||
"bits": 16,
|
||||
"data_type": "fp"
|
||||
},
|
||||
"model.layers.22.self_attn.gate_proj": {
|
||||
"bits": 16,
|
||||
"data_type": "fp"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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