minicpm5-toolcall-code / train_eval.py
DevGwardo's picture
v4: oversampled abstention + metric fix
17b0632 verified
Raw History Blame Contribute Delete
22 kB
"""Train + evaluate a LoRA tool-calling adapter for openbmb/MiniCPM5-1B.
Single-file, no TRL: plain transformers + peft so the job is version-stable.
Usage (inside the job):
python train_eval.py --data /data --out /out --push-to DevGwardo/minicpm5-1b-toolcall
"""
import argparse
import ast
import json
import math
import os
import re
import time
from pathlib import Path
import torch
from peft import LoraConfig, get_peft_model
from transformers import AutoModelForCausalLM, AutoTokenizer, get_cosine_schedule_with_warmup
MODEL_ID = "openbmb/MiniCPM5-1B"
FN_RE = re.compile(r'<function\s+name="([^"]+)"\s*>(.*?)</function>', re.S)
PARAM_RE = re.compile(r'<param\s+name="([^"]+)"\s*>(.*?)</param>', re.S)
CDATA_RE = re.compile(r"^\s*<!\[CDATA\[(.*?)\]\]>\s*$", re.S)
def log(*a):
print(*a, flush=True)
def freeze(v):
if isinstance(v, bool):
return ("bool", v)
if isinstance(v, (int, float)):
return ("num", float(v))
if isinstance(v, str):
s = v.strip()
low = s.lower()
if low in ("true", "false"):
return ("bool", low == "true")
if low in ("null", "none"):
return ("null",)
try:
return freeze(json.loads(s))
except Exception:
pass
try:
return freeze(ast.literal_eval(s))
except Exception:
pass
return ("str", s)
if isinstance(v, (list, tuple)):
return ("list", tuple(freeze(x) for x in v))
if isinstance(v, dict):
return ("dict", tuple(sorted((str(k), freeze(x)) for k, x in v.items())))
return ("str", str(v))
def canon(call):
return (call["name"], tuple(sorted((k, freeze(v)) for k, v in call["arguments"].items())))
def parse_output(text):
calls = []
for m in FN_RE.finditer(text):
name, body = m.group(1), m.group(2)
args = {}
for p in PARAM_RE.finditer(body):
val = p.group(2)
cd = CDATA_RE.match(val)
if cd:
val = cd.group(1)
args[p.group(1)] = val.strip()
calls.append({"name": name, "arguments": args})
return calls
def load_jsonl(path):
with open(path, encoding="utf-8") as f:
return [json.loads(line) for line in f if line.strip()]
def encode(tok, ex, max_len):
"""Tokenize a conversation and supervise every assistant turn (calls and answers)."""
msgs, tools = ex["messages"], ex["tools"]
full_text = tok.apply_chat_template(msgs, tools=tools, tokenize=False)
ids = tok(full_text, add_special_tokens=False)["input_ids"]
if len(ids) > max_len or len(ids) < 4:
return None
labels = [-100] * len(ids)
pos = 0
for k in range(1, len(msgs) + 1):
pref = tok.apply_chat_template(msgs[:k], tools=tools, tokenize=False)
pids = tok(pref, add_special_tokens=False)["input_ids"]
if len(pids) > len(ids):
return None
if ids[: len(pids)] != pids:
n = 0
while n < len(pids) and ids[n] == pids[n]:
n += 1
if n < len(pids) - 8:
return None
end = n
else:
end = len(pids)
if msgs[k - 1]["role"] == "assistant":
for j in range(pos, end):
labels[j] = ids[j]
pos = end
if all(l == -100 for l in labels):
return None
return {"input_ids": ids, "labels": labels}
def make_batches(items, batch_size, shuffle=False):
idx = list(range(len(items)))
if shuffle:
import random
random.shuffle(idx)
for i in range(0, len(idx), batch_size):
yield [items[j] for j in idx[i : i + batch_size]]
def collate(tok, batch):
maxlen = max(len(b["input_ids"]) for b in batch)
pad = tok.pad_token_id
ids = torch.full((len(batch), maxlen), pad, dtype=torch.long)
labels = torch.full((len(batch), maxlen), -100, dtype=torch.long)
mask = torch.zeros((len(batch), maxlen), dtype=torch.long)
for i, b in enumerate(batch):
n = len(b["input_ids"])
ids[i, :n] = torch.tensor(b["input_ids"])
labels[i, :n] = torch.tensor(b["labels"])
mask[i, :n] = 1
return ids, labels, mask
@torch.no_grad()
def evaluate(model, tok, rows, limit, max_new_tokens=192):
model.eval()
prev_cache = model.config.use_cache
model.config.use_cache = True
tok.padding_side = "left"
im_end = tok.convert_tokens_to_ids("<|im_end|>")
rows = rows[:limit] if limit else rows
results = []
for batch in make_batches(rows, 16):
prompts = [
tok.apply_chat_template(r["messages"][:-1], tools=r["tools"], tokenize=False, add_generation_prompt=True)
for r in batch
]
enc = tok(prompts, return_tensors="pt", padding=True, add_special_tokens=False).to(model.device)
out = model.generate(
**enc,
max_new_tokens=max_new_tokens,
do_sample=False,
eos_token_id=im_end,
pad_token_id=tok.pad_token_id,
)
new = out[:, enc["input_ids"].shape[1]:]
# <function>/<param> are registered special tokens (ids 18-21): decoding with
# skip_special_tokens=True silently deletes the tool-call syntax.
texts = [t.split("<|im_end|>")[0].strip() for t in tok.batch_decode(new, skip_special_tokens=False)]
for r, text in zip(batch, texts):
gt = r["messages"][-1].get("tool_calls") or []
pred = parse_output(text)
gt_names = sorted(c["name"] for c in gt)
pred_names = sorted(c["name"] for c in pred)
gt_canon = sorted(canon(c) for c in gt)
pred_canon = sorted(canon(c) for c in pred)
results.append(
{
"expected": gt,
"predicted": pred,
"name_match": gt_names == pred_names,
"exact": gt_canon == pred_canon,
"parse_ok": bool(pred) or not gt,
"is_negative": not gt,
"false_positive": (not gt) and bool(pred),
"text": text[:500],
}
)
tok.padding_side = "right"
model.config.use_cache = prev_cache
n = len(results)
neg = [r for r in results if r["is_negative"]]
pos = [r for r in results if not r["is_negative"]]
metrics = {
"n": n,
"parse_rate": sum(r["parse_ok"] for r in results) / n,
"name_accuracy": sum(r["name_match"] for r in results) / n,
"exact_call_rate": sum(r["exact"] for r in results) / n,
"positive_name_accuracy": sum(r["name_match"] for r in pos) / len(pos) if pos else 0.0,
"positive_exact_rate": sum(r["exact"] for r in pos) / len(pos) if pos else 0.0,
"abstention_accuracy": sum(not r["false_positive"] for r in neg) / len(neg) if neg else 0.0,
"false_positive_rate": sum(r["false_positive"] for r in neg) / len(neg) if neg else 0.0,
}
return metrics, results
def evaluate_mt(model, tok, rows, limit=0):
"""Staged multi-turn eval: stage 1 predicts the call, stage 2 sees the tool result."""
model.eval()
prev_cache = model.config.use_cache
model.config.use_cache = True
tok.padding_side = "left"
im_end = tok.convert_tokens_to_ids("<|im_end|>")
rows = rows[:limit] if limit else rows
def generate(prompts):
texts = []
for batch in make_batches(prompts, 8):
enc = tok(batch, return_tensors="pt", padding=True, add_special_tokens=False).to(model.device)
out = model.generate(
**enc, max_new_tokens=192, do_sample=False, eos_token_id=im_end, pad_token_id=tok.pad_token_id
)
new = out[:, enc["input_ids"].shape[1]:]
texts += [t.split("<|im_end|>")[0].strip() for t in tok.batch_decode(new, skip_special_tokens=False)]
return texts
p1 = [
tok.apply_chat_template(r["messages"][:1], tools=r["tools"], tokenize=False, add_generation_prompt=True)
for r in rows
]
p2 = [
tok.apply_chat_template(r["messages"][:3], tools=r["tools"], tokenize=False, add_generation_prompt=True)
for r in rows
]
pred1 = [parse_output(t) for t in generate(p1)]
t2 = generate(p2)
pred2 = [parse_output(t) for t in t2]
tok.padding_side = "right"
model.config.use_cache = prev_cache
s1 = s2_type = 0
gt2_calls, gt2_text = [], []
for r, a, b, raw2 in zip(rows, pred1, pred2, t2):
gt1 = r["messages"][1].get("tool_calls") or []
if sorted(canon(c) for c in a) == sorted(canon(c) for c in gt1):
s1 += 1
gt2 = r["messages"][3].get("tool_calls") or []
if bool(b) == bool(gt2):
s2_type += 1
if gt2:
gt2_calls.append((b, gt2))
else:
gt2_text.append((b, raw2))
n = max(1, len(rows))
mt = {
"n": len(rows),
"stage1_exact": s1 / n,
"stage2_type_accuracy": s2_type / n,
"stage2_call_exact": (
sum(sorted(canon(c) for c in b) == sorted(canon(c) for c in g) for b, g in gt2_calls) / len(gt2_calls)
if gt2_calls
else None
),
# When the ground truth is an answer, a good model emits no call at all.
"stage2_no_spurious_call_rate": (
sum(not b for b, _ in gt2_text) / len(gt2_text) if gt2_text else None
),
"stage2_answer_rate": (sum(bool(t.strip()) for _, t in gt2_text) / len(gt2_text)) if gt2_text else None,
}
return mt
def write_card(path, metrics_base, metrics_tuned, repo_id, dataset_id, mt_base=None, mt_tuned=None):
def fmt(x):
return "n/a" if x is None else f"{x:.3f}"
table = "\n".join(
f"| {k} | {metrics_base[k]:.3f} | {metrics_tuned[k]:.3f} |"
for k in ("exact_call_rate", "name_accuracy", "parse_rate", "abstention_accuracy", "false_positive_rate")
)
mt_section = ""
if mt_base and mt_tuned:
mt_section = f"""
## Multi-turn loops
One round trip is: user -> call -> tool result -> follow-up. Stage 1 checks the first call.
Stage 2 appends the ground-truth tool result and checks whether the model answers or calls again.
100 held-out loops, greedy decoding, identical prompts for both models.
| Stage | Base | + LoRA |
|-------|------|--------|
| Stage 1: first call exact | {mt_base['stage1_exact']:.3f} | {mt_tuned['stage1_exact']:.3f} |
| Stage 2: call-vs-answer decision | {mt_base['stage2_type_accuracy']:.3f} | {mt_tuned['stage2_type_accuracy']:.3f} |
| Stage 2: second call exact | {fmt(mt_base['stage2_call_exact'])} | {fmt(mt_tuned['stage2_call_exact'])} |
| Stage 2: non-empty answer | {fmt(mt_base['stage2_answer_rate'])} | {fmt(mt_tuned['stage2_answer_rate'])} |
"""
path.write_text(
f"""---
base_model: {MODEL_ID}
library_name: peft
pipeline_tag: text-generation
license: apache-2.0
language:
- en
tags:
- lora
- function-calling
- tool-use
- multi-turn
- minicpm
datasets:
- {dataset_id}
---
# MiniCPM5-1B ToolCall LoRA
A LoRA adapter for [`{MODEL_ID}`](https://huggingface.co/{MODEL_ID}) that raises exact tool-call
accuracy and fixes over-calling, including **multi-turn loops** (call -> tool result -> follow-up).
The base model already supports XML tool calling; this adapter is not "teaching" the format. It is
a measured improvement on a reproducible held-out benchmark, trained with completion-only loss.
Trained on [`{dataset_id}`](https://huggingface.co/datasets/{dataset_id}) (derived from ToolACE,
Apache-2.0): 6,500 single-turn call examples, 1,100 abstention examples, and 590 held-out-safe
multi-turn loops. LoRA r=16 on all linear layers, 2 epochs, max 1,024 tokens.
## Results
Greedy decoding on a 500-example held-out split (400 calls + 100 abstention).
| Metric | Base | + LoRA |
|--------|------|--------|
{table}
- `exact_call_rate` — function names **and** every argument match
- `abstention_accuracy` — answers without calling a tool when none is needed
- `false_positive_rate` — invents a call on an abstention prompt (lower is better)
{mt_section}
## Usage
```python
from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import PeftModel
base = AutoModelForCausalLM.from_pretrained("{MODEL_ID}", dtype="bfloat16", device_map="auto")
model = PeftModel.from_pretrained(base, "{repo_id}")
tok = AutoTokenizer.from_pretrained("{repo_id}")
messages = [{{"role": "user", "content": "What's the weather in Paris in celsius?"}}]
tools = [{{
"name": "get_weather",
"description": "Get current weather for a location",
"parameters": {{"type": "object", "properties": {{
"location": {{"type": "string"}}, "units": {{"type": "string", "enum": ["celsius", "fahrenheit"]}}
}}, "required": ["location"]}},
}}]
prompt = tok.apply_chat_template(messages, tools=tools, tokenize=False, add_generation_prompt=True)
inputs = tok(prompt, return_tensors="pt").to(model.device)
new = model.generate(**inputs, max_new_tokens=192)[0][inputs["input_ids"].shape[1]:]
# <function>/<param> are special tokens: keep them in the decoded text.
print(tok.decode(new, skip_special_tokens=False).split("<|im_end|>")[0].strip())
```
## Limitations
- One tool round per conversation in training; longer chains are untested.
- English/Chinese source data; argument values are normalized, not copied verbatim.
- Greedy decoding only; no sampling/temperature sweep.
## Provenance
Derived from [Team-ACE/ToolACE](https://huggingface.co/datasets/Team-ACE/ToolACE) (Apache-2.0).
Test rows are held out before training; `predictions.jsonl` contains the raw generations used
for the table above.
""",
encoding="utf-8",
)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--data", default="/data")
ap.add_argument("--out", default="out")
ap.add_argument("--epochs", type=float, default=2)
ap.add_argument("--lr", type=float, default=1e-4)
ap.add_argument("--batch", type=int, default=2)
ap.add_argument("--accum", type=int, default=8)
ap.add_argument("--max-len", type=int, default=1024)
ap.add_argument("--max-train", type=int, default=0)
ap.add_argument("--eval-limit", type=int, default=0)
ap.add_argument("--push-to", default="")
ap.add_argument("--train-file", default="train.jsonl")
ap.add_argument("--extra-train", default="", help="extra JSONL of conversations (multi-turn) to append to train")
ap.add_argument("--multiturn-test", default="", help="JSONL of 4-message loops for staged evaluation")
ap.add_argument("--adapter", default="", help="eval-only: load this adapter repo instead of training")
ap.add_argument("--dataset-id", default="DevGwardo/toolcall-mini")
args = ap.parse_args()
out = Path(args.out)
out.mkdir(parents=True, exist_ok=True)
data = Path(args.data)
device = "cuda" if torch.cuda.is_available() else "cpu"
log(f"device={device} torch={torch.__version__}")
tok = AutoTokenizer.from_pretrained(MODEL_ID)
if tok.pad_token is None:
tok.pad_token = tok.eos_token
tok.padding_side = "right"
log("loading data...")
train_rows = load_jsonl(data / args.train_file)
val_rows = load_jsonl(data / "val.jsonl")
test_rows = load_jsonl(data / "test.jsonl")
if args.extra_train and Path(args.extra_train).exists():
extra = load_jsonl(Path(args.extra_train))
train_rows = train_rows + extra
log(f"extra multi-turn train rows: {len(extra)}")
mt_rows = []
if args.multiturn_test and Path(args.multiturn_test).exists():
mt_rows = load_jsonl(Path(args.multiturn_test))
log(f"multi-turn test rows: {len(mt_rows)}")
if args.max_train:
train_rows = train_rows[: args.max_train]
train = [e for e in (encode(tok, r, args.max_len) for r in train_rows) if e]
val = [e for e in (encode(tok, r, args.max_len) for r in val_rows) if e]
log(f"train={len(train)} val={len(val)} test={len(test_rows)}")
log("loading model...")
dtype = torch.bfloat16 if device == "cuda" else torch.float32
model = AutoModelForCausalLM.from_pretrained(
MODEL_ID, dtype=dtype, attn_implementation="sdpa", use_kernels=False
)
model.to(device)
log("evaluating base...")
t0 = time.time()
metrics_base, _ = evaluate(model, tok, test_rows, args.eval_limit)
log("BASE", json.dumps(metrics_base))
mt_base = evaluate_mt(model, tok, mt_rows, args.eval_limit) if mt_rows else None
if mt_base:
log("BASE_MT", json.dumps(mt_base))
log(f"base eval {time.time() - t0:.0f}s")
lora = LoraConfig(
r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM", target_modules="all-linear"
)
if args.adapter:
from peft import PeftModel
log(f"loading adapter {args.adapter} (eval-only)")
model = PeftModel.from_pretrained(model, args.adapter)
model.eval()
vl, done, adapter_dir = None, 0, None
else:
model = get_peft_model(model, lora)
model.print_trainable_parameters()
try:
model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False})
except TypeError:
model.gradient_checkpointing_enable()
try:
model.enable_input_require_grads()
except AttributeError:
model.base_model.model.enable_input_require_grads()
model.config.use_cache = False
steps_per_epoch = math.ceil(len(train) / (args.batch * args.accum))
total_steps = max(1, int(steps_per_epoch * args.epochs))
opt = torch.optim.AdamW([p for p in model.parameters() if p.requires_grad], lr=args.lr, weight_decay=0.01)
sched = get_cosine_schedule_with_warmup(opt, max(1, int(total_steps * 0.03)), total_steps)
model.train()
done = 0
for epoch in range(math.ceil(args.epochs)):
if done >= total_steps:
break
for i, batch in enumerate(make_batches(train, args.batch, shuffle=True)):
if done >= total_steps:
break
ids, labels, mask = collate(tok, batch)
ids, labels, mask = ids.to(device), labels.to(device), mask.to(device)
with torch.autocast("cuda", dtype=torch.bfloat16, enabled=(device == "cuda")):
loss = model(input_ids=ids, attention_mask=mask, labels=labels).loss
(loss / args.accum).backward()
if (i + 1) % args.accum == 0:
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step()
sched.step()
opt.zero_grad()
done += 1
if done % 20 == 0 or done == total_steps:
log(f"step {done}/{total_steps} loss={loss.item():.4f} lr={sched.get_last_lr()[0]:.2e}")
adapter_dir = out / "adapter"
model.save_pretrained(adapter_dir)
tok.save_pretrained(adapter_dir)
@torch.no_grad()
def val_loss():
model.eval()
total, n = 0.0, 0
for batch in make_batches(val, args.batch):
ids, labels, mask = collate(tok, batch)
ids, labels, mask = ids.to(device), labels.to(device), mask.to(device)
with torch.autocast("cuda", dtype=torch.bfloat16, enabled=(device == "cuda")):
l = model(input_ids=ids, attention_mask=mask, labels=labels).loss
total += l.item() * len(batch)
n += len(batch)
model.train()
return total / max(1, n)
vl = val_loss()
log(f"val_loss={vl:.4f}")
log("evaluating tuned...")
metrics_tuned, details = evaluate(model, tok, test_rows, args.eval_limit)
log("TUNED", json.dumps(metrics_tuned))
mt_tuned = evaluate_mt(model, tok, mt_rows, args.eval_limit) if mt_rows else None
if mt_tuned:
log("TUNED_MT", json.dumps(mt_tuned))
metrics = {
"base": metrics_base,
"tuned": metrics_tuned,
"multiturn_base": mt_base,
"multiturn_tuned": mt_tuned,
"val_loss": vl,
"steps": done,
}
(out / "metrics.json").write_text(json.dumps(metrics, indent=2))
(out / "predictions.jsonl").write_text(
"\n".join(json.dumps(d, ensure_ascii=False) for d in details[:200]), encoding="utf-8"
)
if args.push_to:
from huggingface_hub import HfApi
repo = args.push_to
card_path = (adapter_dir / "README.md") if adapter_dir else (out / "README.md")
write_card(card_path, metrics_base, metrics_tuned, repo, args.dataset_id, mt_base, mt_tuned)
api = HfApi(token=os.environ.get("HF_TOKEN"))
api.create_repo(repo, repo_type="model", exist_ok=True, private=False)
if adapter_dir:
api.upload_folder(folder_path=str(adapter_dir), repo_id=repo, commit_message="Add tool-calling LoRA + eval")
api.upload_file(path_or_fileobj=str(out / "metrics.json"), path_in_repo="metrics.json", repo_id=repo)
api.upload_file(
path_or_fileobj=str(out / "predictions.jsonl"), path_in_repo="predictions.jsonl", repo_id=repo
)
log(f"pushed https://huggingface.co/{repo}")
if __name__ == "__main__":
main()