Fix special-token decoding + eval-only mode
Browse filesFiles changed (2)
- check_special.pyAdded+7
- train_eval.py+79-62
1234567from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("openbmb/MiniCPM5-1B")for t in ["<function", "</function>", "<param", "</param>", "<|im_end|>", "<tools>", "</tools>"]: print(repr(t), "id:", tok.convert_tokens_to_ids(t))print("special tokens containing 'function' or 'param':")print([t for t in tok.all_special_tokens if "function" in t or "param" in t])146 unmodified lines14714814915015015115215315415595 unmodified lines25125225325225425525625725825918 unmodified lines27827928028128228328434 unmodified lines3193203213173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613223233243253263273283633643653663673683693703713723293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873743753883893903913929 unmodified lines402403404405391406407408409394410411412396413414415416146 unmodified lines pad_token_id=tok.pad_token_id, ) new = out[:, enc["input_ids"].shape[1]:] texts = tok.batch_decode(new, skip_special_tokens=True) # <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)95 unmodified lines
prompt = tok.apply_chat_template(messages, tools=tools, tokenize=False, add_generation_prompt=True)inputs = tok(prompt, return_tensors="pt").to(model.device)print(tok.decode(model.generate(**inputs, max_new_tokens=192)[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True))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())```
## Limitations18 unmodified lines 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("--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()
34 unmodified lines lora = LoraConfig( r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM", target_modules="all-linear" ) 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():
if args.adapter: from peft import PeftModel
log(f"loading adapter {args.adapter} (eval-only)") model = PeftModel.from_pretrained(model, args.adapter) 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, 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}") vl = val_loss() log(f"val_loss={vl:.4f}")
log("evaluating tuned...") metrics_tuned, details = evaluate(model, tok, test_rows, args.eval_limit)9 unmodified lines from huggingface_hub import HfApi
repo = args.push_to card_path = (adapter_dir / "README.md") if adapter_dir else (out / "README.md") write_card(adapter_dir / "README.md", metrics_base, metrics_tuned, repo, args.dataset_id) write_card(card_path, metrics_base, metrics_tuned, repo, args.dataset_id) 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_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 / "metrics.json"), path_in_repo="metrics.json", repo_id=repo path_or_fileobj=str(out / "predictions.jsonl"), path_in_repo="predictions.jsonl", repo_id=repo ) log(f"pushed https://huggingface.co/{repo}")
check_special.pyAdded+7
train_eval.py+79-62