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>
106 lines
5.3 KiB
Python
106 lines
5.3 KiB
Python
#!/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}")
|