File size: 21,984 Bytes
17e10c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0dad616
17e10c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17b0632
 
17e10c6
 
 
 
 
 
17b0632
17e10c6
 
 
 
 
 
 
 
 
17b0632
17e10c6
 
 
 
 
 
 
 
 
 
 
17b0632
 
 
 
 
17e10c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17b0632
17e10c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17b0632
17e10c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
"""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()