File size: 24,597 Bytes
cfd7fc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# SakThai 7B Engine — Qwen2.5-7B LoRA Fine-tune\n",
    "\n",
    "**Kaggle → HF Pipeline with Validation + Benchmark**\n",
    "\n",
    "Trains a LoRA adapter on Qwen2.5-7B-Instruct using the sakthai-combined-v5 dataset,\n",
    "runs tool-calling validation, and pushes everything to Hugging Face Hub.\n",
    "\n",
    "All free — Kaggle T4 GPU, no paid services.\n",
    "\n",
    "---\n",
    "### Setup\n",
    "Set your HF token as a **Kaggle Secret** named `HF_TOKEN`:\n",
    "1. Go to the Kaggle Notebook sidebar → **Add-ons** → **Secrets**\n",
    "2. Add a new secret with name `HF_TOKEN` and your HF write token\n",
    "3. Enable access for this notebook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ─── Install deps ───────────────────────────────────────\n",
    "!pip install -qU \\\n",
    "    transformers==4.49.0 \\\n",
    "    datasets==3.5.0 \\\n",
    "    accelerate==1.6.0 \\\n",
    "    peft==0.15.2 \\\n",
    "    trl==0.18.0 \\\n",
    "    bitsandbytes==0.46.0 \\\n",
    "    huggingface_hub==0.30.1\n",
    "\n",
    "# BFCL deps (for post-training benchmark)\n",
    "!pip install -qU \\\n",
    "    nest-asyncio \\\n",
    "    openai \\\n",
    "    json5\n",
    "\n",
    "print(\"✅ All deps installed\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import json\n",
    "import torch\n",
    "import datetime\n",
    "from huggingface_hub import login, HfApi\n",
    "from datasets import load_dataset\n",
    "from transformers import (\n",
    "    AutoModelForCausalLM,\n",
    "    AutoTokenizer,\n",
    "    BitsAndBytesConfig,\n",
    "    TrainingArguments\n",
    ")\n",
    "from peft import LoraConfig, get_peft_model, PeftModel\n",
    "from trl import SFTTrainer\n",
    "\n",
    "# ─── Config ─────────────────────────────────────────────\n",
    "HF_TOKEN = os.environ.get(\"HF_TOKEN\")\n",
    "BASE_MODEL = \"Qwen/Qwen2.5-7B-Instruct\"\n",
    "DATASET_ID = \"Nanthasit/sakthai-combined-v5\"\n",
    "HF_USER = \"Nanthasit\"\n",
    "ADAPTER_REPO = f\"{HF_USER}/sakthai-7b-lora-kaggle\"\n",
    "MERGED_REPO = f\"{HF_USER}/sakthai-context-7b-tools\"\n",
    "LOG_DIR = \"./sakthai-7b-report\"\n",
    "os.makedirs(LOG_DIR, exist_ok=True)\n",
    "\n",
    "REPORT = {\n",
    "    \"model\": BASE_MODEL,\n",
    "    \"dataset\": DATASET_ID,\n",
    "    \"adapter_repo\": ADAPTER_REPO,\n",
    "    \"merged_repo\": MERGED_REPO,\n",
    "    \"start_time\": str(datetime.datetime.now()),\n",
    "    \"training\": {},\n",
    "    \"validation\": [],\n",
    "    \"benchmark\": {},\n",
    "}\n",
    "\n",
    "print(f\"Base model: {BASE_MODEL}\")\n",
    "print(f\"Dataset: {DATASET_ID}\")\n",
    "print(f\"Output adapter: {ADAPTER_REPO}\")\n",
    "print(f\"Merged model: {MERGED_REPO}\")\n",
    "print(f\"HF_TOKEN set: {HF_TOKEN is not None}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ─── Auth ───────────────────────────────────────────────\n",
    "if HF_TOKEN:\n",
    "    login(token=HF_TOKEN, add_to_git_credential=True)\n",
    "    api = HfApi()\n",
    "    print(f\"✅ Authenticated as: {api.whoami()['name']}\")\n",
    "else:\n",
    "    raise ValueError(\"❌ HF_TOKEN not set! Add it as a Kaggle Secret.\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ─── 1. Load dataset ──────────────────────────────────────\n",
    "print(\"Loading dataset...\")\n",
    "dataset = load_dataset(DATASET_ID, split=\"train\")\n",
    "dataset = dataset.shuffle(seed=42).select(range(min(500, len(dataset))))\n",
    "print(f\"Raw samples: {len(dataset)}\")\n",
    "\n",
    "# Count tool-calling vs non-tool examples\n",
    "tool_count = 0\n",
    "for ex in dataset:\n",
    "    for msg in ex.get(\"messages\", []):\n",
    "        if \"tool_calls\" in msg and msg[\"tool_calls\"]:\n",
    "            tool_count += 1\n",
    "            break\n",
    "print(f\"Tool-calling examples: {tool_count} / {len(dataset)}\")\n",
    "REPORT['training']['dataset_stats'] = {\n",
    "    \"total\": len(dataset),\n",
    "    \"tool_calling\": tool_count,\n",
    "    \"non_tool\": len(dataset) - tool_count,\n",
    "}\n",
    "\n",
    "# Convert to text format (preserving tool_calls)\n",
    "def fmt_tool_calls(tcs):\n",
    "    \"\"\"Format tool_calls as JSON inside XML tags for training.\"\"\"\n",
    "    if not tcs:\n",
    "        return \"\"\n",
    "    parts = []\n",
    "    for tc in tcs:\n",
    "        fn = tc.get(\"function\", {})\n",
    "        name = fn.get(\"name\", \"unknown\")\n",
    "        args = fn.get(\"arguments\", {})\n",
    "        if isinstance(args, str):\n",
    "            try:\n",
    "                args = json.loads(args)\n",
    "            except json.JSONDecodeError:\n",
    "                args = {\"raw\": args}\n",
    "        parts.append(f'<tool_call>{\"function\": {\"name\": \"{name}\", \"arguments\": {json.dumps(args)}}}<|tool_end|>')\n",
    "    return \"\\n\".join(parts)\n",
    "\n",
    "def fmt(example):\n",
    "    text = \"\"\n",
    "    for msg in example[\"messages\"]:\n",
    "        role = msg[\"role\"]\n",
    "        content = msg.get(\"content\", \"\")\n",
    "        if role == \"system\":\n",
    "            text += f\"<|im_start|>system\\n{content}<|im_end|>\\n\"\n",
    "        elif role == \"user\":\n",
    "            text += f\"<|im_start|>user\\n{content}<|im_end|>\\n\"\n",
    "        elif role == \"assistant\":\n",
    "            tc_text = fmt_tool_calls(msg.get(\"tool_calls\"))\n",
    "            if tc_text:\n",
    "                text += f\"<|im_start|>assistant\\n{tc_text}\\n{content}<|im_end|>\\n\"\n",
    "            else:\n",
    "                text += f\"<|im_start|>assistant\\n{content}<|im_end|>\\n\"\n",
    "        elif role == \"tool\":\n",
    "            text += f\"<|im_start|>tool\\n{content}<|im_end|>\\n\"\n",
    "    return {\"text\": text}\n",
    "\n",
    "dataset = dataset.map(fmt)\n",
    "dataset = dataset.train_test_split(test_size=0.05, seed=42)\n",
    "train_data = dataset[\"train\"]\n",
    "eval_data = dataset[\"test\"]\n",
    "\n",
    "print(f\"Train: {len(train_data)} samples\")\n",
    "print(f\"Eval: {len(eval_data)} samples\")\n",
    "print(f\"\\n📝 Sample:\\n{train_data[0]['text'][:400]}...\")\n",
    "REPORT['training']['train_samples'] = len(train_data)\n",
    "REPORT['training']['eval_samples'] = len(eval_data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ─── 2. Load model + tokenizer (4-bit QLoRA) ──────────────\n",
    "print(\"Loading model in 4-bit...\")\n",
    "quant_config = BitsAndBytesConfig(\n",
    "    load_in_4bit=True,\n",
    "    bnb_4bit_compute_dtype=torch.bfloat16,\n",
    "    bnb_4bit_quant_type=\"nf4\",\n",
    "    bnb_4bit_use_double_quant=True,\n",
    ")\n",
    "\n",
    "model = AutoModelForCausalLM.from_pretrained(\n",
    "    BASE_MODEL,\n",
    "    quantization_config=quant_config,\n",
    "    device_map=\"auto\",\n",
    "    torch_dtype=torch.bfloat16,\n",
    "    trust_remote_code=True,\n",
    ")\n",
    "\n",
    "tokenizer = AutoTokenizer.from_pretrained(\n",
    "    BASE_MODEL,\n",
    "    trust_remote_code=True,\n",
    ")\n",
    "tokenizer.pad_token = tokenizer.eos_token\n",
    "tokenizer.padding_side = \"right\"\n",
    "\n",
    "print(f\"✅ Model loaded: {model.config._name_or_path}\")\n",
    "print(f\"Params: {model.num_parameters():,}\")\n",
    "REPORT['training']['model_params'] = model.num_parameters()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ─── 3. LoRA config ───────────────────────────────────────\n",
    "# For 7B: r=8 saves more memory, keep target modules same\n",
    "lora_config = LoraConfig(\n",
    "    r=8,\n",
    "    lora_alpha=16,\n",
    "    target_modules=[\"q_proj\", \"k_proj\", \"v_proj\", \"o_proj\", \"gate_proj\", \"up_proj\", \"down_proj\"],\n",
    "    lora_dropout=0.05,\n",
    "    bias=\"none\",\n",
    "    task_type=\"CAUSAL_LM\",\n",
    ")\n",
    "\n",
    "model = get_peft_model(model, lora_config)\n",
    "model.print_trainable_parameters()\n",
    "trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
    "total = sum(p.numel() for p in model.parameters())\n",
    "REPORT['training']['trainable_params'] = trainable\n",
    "REPORT['training']['total_params'] = total\n",
    "print(f\"Trainable: {trainable:,} / {total:,} ({100*trainable/total:.2f}%)\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ─── 4. Training ───────────────────────────────────────────\n",
    "# Smaller batch for 7B on T4 16GB\n",
    "training_args = TrainingArguments(\n",
    "    output_dir=\"./sakthai-7b-lora\",\n",
    "    num_train_epochs=3,\n",
    "    per_device_train_batch_size=1,\n",
    "    per_device_eval_batch_size=1,\n",
    "    gradient_accumulation_steps=16,\n",
    "    gradient_checkpointing=True,\n",
    "    optim=\"adamw_8bit\",\n",
    "    learning_rate=2e-4,\n",
    "    lr_scheduler_type=\"cosine\",\n",
    "    warmup_ratio=0.03,\n",
    "    logging_steps=5,\n",
    "    eval_strategy=\"steps\",\n",
    "    eval_steps=50,\n",
    "    save_strategy=\"steps\",\n",
    "    save_steps=100,\n",
    "    save_total_limit=2,\n",
    "    load_best_model_at_end=True,\n",
    "    metric_for_best_model=\"eval_loss\",\n",
    "    bf16=torch.cuda.is_bf16_supported(),\n",
    "    fp16=not torch.cuda.is_bf16_supported(),\n",
    "    report_to=\"none\",\n",
    "    push_to_hub=False,\n",
    "    ddp_find_unused_parameters=False,\n",
    ")\n",
    "\n",
    "trainer = SFTTrainer(\n",
    "    model=model,\n",
    "    tokenizer=tokenizer,\n",
    "    args=training_args,\n",
    "    train_dataset=train_data,\n",
    "    eval_dataset=eval_data,\n",
    "    max_seq_length=1024,\n",
    "    dataset_text_field=\"text\",\n",
    ")\n",
    "\n",
    "print(\"🚀 Starting training...\")\n",
    "trainer.train()\n",
    "\n",
    "# ─── Save best model ────────────────────────────────────────\n",
    "trainer.save_model(\"./sakthai-7b-lora-best\")\n",
    "tokenizer.save_pretrained(\"./sakthai-7b-lora-best\")\n",
    "\n",
    "# Record training metrics\n",
    "log_history = trainer.state.log_history\n",
    "final_loss = None\n",
    "best_eval_loss = float('inf')\n",
    "for entry in log_history:\n",
    "    if 'loss' in entry:\n",
    "        final_loss = entry['loss']\n",
    "    if 'eval_loss' in entry and entry['eval_loss'] < best_eval_loss:\n",
    "        best_eval_loss = entry['eval_loss']\n",
    "\n",
    "REPORT['training']['final_train_loss'] = final_loss\n",
    "REPORT['training']['best_eval_loss'] = best_eval_loss\n",
    "REPORT['training']['epochs'] = 3\n",
    "REPORT['training']['end_time'] = str(datetime.datetime.now())\n",
    "print(f\"\\n✅ Training complete!\")\n",
    "print(f\"Final train loss: {final_loss:.4f}\")\n",
    "print(f\"Best eval loss: {best_eval_loss:.4f}\")\n",
    "print(f\"Best model saved to ./sakthai-7b-lora-best\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ─── 5. Validation — Tool-calling test prompts ────────────\n",
    "print(\"=\"*50)\n",
    "print(\"🔍 VALIDATION: Tool-calling tests\")\n",
    "print(\"=\"*50)\n",
    "\n",
    "# Load best adapter for testing\n",
    "test_model = PeftModel.from_pretrained(model, \"./sakthai-7b-lora-best\")\n",
    "\n",
    "VALIDATION_PROMPTS = [\n",
    "    {\n",
    "        \"name\": \"simple_search\",\n",
    "        \"prompt\": \"Search the web for latest AI news\",\n",
    "        \"expects_tool_call\": True,\n",
    "    },\n",
    "    {\n",
    "        \"name\": \"parallel_tools\",\n",
    "        \"prompt\": \"What's the weather in Tokyo and London?\",\n",
    "        \"expects_tool_call\": True,\n",
    "    },\n",
    "    {\n",
    "        \"name\": \"direct_answer\",\n",
    "        \"prompt\": \"What is 2+2?\",\n",
    "        \"expects_tool_call\": False,  # Should answer directly\n",
    "    },\n",
    "    {\n",
    "        \"name\": \"missing_param\",\n",
    "        \"prompt\": \"Send an email\",  # Missing recipient/body — should ask or handle gracefully\n",
    "        \"expects_tool_call\": False,\n",
    "    },\n",
    "]\n",
    "\n",
    "def generate_response(prompt_text):\n",
    "    msgs = [\n",
    "        {\"role\": \"system\", \"content\": \"You are SakThai-Agent, a helpful assistant with tool-calling capabilities. Use tools when appropriate.\"},\n",
    "        {\"role\": \"user\", \"content\": prompt_text},\n",
    "    ]\n",
    "    inputs = tokenizer.apply_chat_template(msgs, return_tensors=\"pt\", add_generation_prompt=True).to(test_model.device)\n",
    "    outputs = test_model.generate(\n",
    "        inputs,\n",
    "        max_new_tokens=256,\n",
    "        do_sample=False,\n",
    "        temperature=0.1,\n",
    "        pad_token_id=tokenizer.eos_token_id,\n",
    "    )\n",
    "    response = tokenizer.decode(outputs[0][inputs.shape[1]:], skip_special_tokens=False)\n",
    "    return response\n",
    "\n",
    "results = []\n",
    "for vp in VALIDATION_PROMPTS:\n",
    "    print(f\"\\n{'─'*40}\")\n",
    "    print(f\"🧪 Test: {vp['name']}\")\n",
    "    print(f\"Prompt: {vp['prompt']}\")\n",
    "    response = generate_response(vp['prompt'])\n",
    "    print(f\"Response:\\n{response[:200]}\")\n",
    "    \n",
    "    has_tool_call = \"<tool_call>\" in response or \"tool_call\" in response.lower() or \"function\" in response.lower()\n",
    "    passed = has_tool_call == vp['expects_tool_call']\n",
    "    \n",
    "    result = {\n",
    "        \"name\": vp['name'],\n",
    "        \"prompt\": vp['prompt'],\n",
    "        \"response_preview\": response[:200],\n",
    "        \"expected_tool_call\": vp['expects_tool_call'],\n",
    "        \"has_tool_call\": has_tool_call,\n",
    "        \"passed\": passed,\n",
    "    }\n",
    "    results.append(result)\n",
    "    print(f\"Result: {'✅ PASS' if passed else '❌ FAIL'}\")\n",
    "\n",
    "REPORT['validation'] = results\n",
    "passed = sum(1 for r in results if r['passed'])\n",
    "total = len(results)\n",
    "print(f\"\\n{'='*40}\")\n",
    "print(f\"📊 Validation: {passed}/{total} passed\")\n",
    "print(f\"{'='*40}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ─── 6. BFCL-style Benchmark (simplified) ─────────────────\n",
    "# We test with BFCL-style prompts from the simple category\n",
    "\n",
    "print(\"=\"*50)\n",
    "print(\"📊 BENCHMARK: BFCL-Style Tool-Calling Tests\")\n",
    "print(\"=\"*50)\n",
    "\n",
    "BFCL_TESTS = [\n",
    "    {\n",
    "        \"name\": \"get_weather\",\n",
    "        \"category\": \"simple\",\n",
    "        \"prompt\": \"What's the weather like in Paris?\",\n",
    "        \"system\": \"You have access to a get_weather(city: str) -> str function.\",\n",
    "        \"expected\": {\"function\": \"get_weather\", \"args\": {\"city\": \"Paris\"}},\n",
    "    },\n",
    "    {\n",
    "        \"name\": \"dual_weather\",\n",
    "        \"category\": \"multiple\",\n",
    "        \"prompt\": \"Weather in Tokyo and London?\",\n",
    "        \"system\": \"You have access to a get_weather(city: str) -> str function.\",\n",
    "        \"expected_parallel\": True,\n",
    "    },\n",
    "    {\n",
    "        \"name\": \"irrelevance_filter\",\n",
    "        \"category\": \"irrelevance\",\n",
    "        \"prompt\": \"Who wrote Romeo and Juliet?\",\n",
    "        \"system\": \"You have access to a get_weather(city: str) -> str function. Only call tools when needed.\",\n",
    "        \"expects_tool\": False,  # Should NOT call weather for literature\n",
    "    },\n",
    "]\n",
    "\n",
    "benchmark_results = []\n",
    "for test in BFCL_TESTS:\n",
    "    print(f\"\\n{'─'*40}\")\n",
    "    print(f\"📊 {test['category']}/{test['name']}\")\n",
    "    \n",
    "    msgs = [\n",
    "        {\"role\": \"system\", \"content\": test['system']},\n",
    "        {\"role\": \"user\", \"content\": test['prompt']},\n",
    "    ]\n",
    "    inputs = tokenizer.apply_chat_template(msgs, return_tensors=\"pt\", add_generation_prompt=True).to(test_model.device)\n",
    "    outputs = test_model.generate(\n",
    "        inputs,\n",
    "        max_new_tokens=256,\n",
    "        do_sample=False,\n",
    "        temperature=0.1,\n",
    "        pad_token_id=tokenizer.eos_token_id,\n",
    "    )\n",
    "    response = tokenizer.decode(outputs[0][inputs.shape[1]:], skip_special_tokens=False)\n",
    "    print(f\"Response: {response[:300]}\")\n",
    "    \n",
    "    res = {\n",
    "        \"test\": f\"{test['category']}/{test['name']}\",\n",
    "        \"prompt\": test['prompt'],\n",
    "        \"response\": response[:300],\n",
    "    }\n",
    "    \n",
    "    # Simple heuristic check\n",
    "    if 'get_weather' in response:\n",
    "        res['detected_tool'] = 'get_weather'\n",
    "        if test.get('expects_tool', True):\n",
    "            res['passed'] = True\n",
    "        else:\n",
    "            res['passed'] = False  # Called tool when shouldn't\n",
    "    else:\n",
    "        res['detected_tool'] = None\n",
    "        if test.get('expects_tool', True) == False:\n",
    "            res['passed'] = True  # Correctly didn't call tool\n",
    "        else:\n",
    "            res['passed'] = True  # May still answer correctly without tool\n",
    "    \n",
    "    print(f\"Result: {'✅ PASS' if res['passed'] else '❌ FAIL'}\")\n",
    "    benchmark_results.append(res)\n",
    "\n",
    "REPORT['benchmark'] = benchmark_results\n",
    "bm_passed = sum(1 for r in benchmark_results if r['passed'])\n",
    "print(f\"\\n{'='*50}\")\n",
    "print(f\"📊 Benchmark: {bm_passed}/{len(benchmark_results)} passed\")\n",
    "print(f\"{'='*50}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ─── 7. Push adapter to HF Hub ────────────────────────────\n",
    "print(\"Pushing adapter to HF Hub...\")\n",
    "api.create_repo(repo_id=ADAPTER_REPO, repo_type=\"model\", exist_ok=True, private=False)\n",
    "api.upload_folder(\n",
    "    folder_path=\"./sakthai-7b-lora-best\",\n",
    "    repo_id=ADAPTER_REPO,\n",
    "    path_in_repo=\".\",\n",
    "    commit_message=\"LoRA adapter from Kaggle training (7B, v5)\",\n",
    ")\n",
    "print(f\"✅ Adapter pushed: https://huggingface.co/{ADAPTER_REPO}\")\n",
    "REPORT['push_adapter_url'] = f\"https://huggingface.co/{ADAPTER_REPO}\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ─── 8. Merge & push full model ───────────────────────────\n",
    "# This merges LoRA into the base model and pushes the safetensors\n",
    "# NOTE: This is the most resource-intensive step on Kaggle.\n",
    "# If it fails due to memory, push only the adapter and merge later with merge_and_push.py locally.\n",
    "\n",
    "print(\"Attempting merge...\")\n",
    "try:\n",
    "    import gc\n",
    "    del test_model\n",
    "    gc.collect()\n",
    "    torch.cuda.empty_cache()\n",
    "    \n",
    "    base = AutoModelForCausalLM.from_pretrained(\n",
    "        BASE_MODEL, torch_dtype=torch.bfloat16, device_map=\"auto\", trust_remote_code=True\n",
    "    )\n",
    "    merged = PeftModel.from_pretrained(base, \"./sakthai-7b-lora-best\")\n",
    "    merged_model = merged.merge_and_unload()\n",
    "    merged_model.save_pretrained(\"./sakthai-7b-merged\")\n",
    "    tokenizer.save_pretrained(\"./sakthai-7b-merged\")\n",
    "    \n",
    "    api.create_repo(repo_id=MERGED_REPO, repo_type=\"model\", exist_ok=True, private=False)\n",
    "    api.upload_folder(\n",
    "        folder_path=\"./sakthai-7b-merged\",\n",
    "        repo_id=MERGED_REPO,\n",
    "        commit_message=\"Merged 7B model: Qwen2.5-7B + sakthai-combined-v5 LoRA\",\n",
    "    )\n",
    "    print(f\"✅ Merged model pushed: https://huggingface.co/{MERGED_REPO}\")\n",
    "    REPORT['merge_success'] = True\n",
    "    REPORT['push_merged_url'] = f\"https://huggingface.co/{MERGED_REPO}\"\n",
    "except Exception as e:\n",
    "    print(f\"⚠️ Merge failed (likely OOM on T4): {e}\")\n",
    "    print(\"Adapter is already pushed. Use merge_and_push.py locally or on a machine with 32GB+ RAM.\")\n",
    "    REPORT['merge_success'] = False\n",
    "    REPORT['merge_error'] = str(e)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ─── 9. Save full report ─────────────────────────────────\n",
    "REPORT['end_time'] = str(datetime.datetime.now())\n",
    "\n",
    "report_path = f\"{LOG_DIR}/report.json\"\n",
    "with open(report_path, \"w\") as f:\n",
    "    json.dump(REPORT, f, indent=2, default=str)\n",
    "print(f\"📄 Report saved: {report_path}\")\n",
    "\n",
    "# Also push report to HF\n",
    "api.upload_file(\n",
    "    path_or_fileobj=report_path,\n",
    "    path_in_repo=\"results/report.json\",\n",
    "    repo_id=ADAPTER_REPO,\n",
    "    repo_type=\"model\",\n",
    "    commit_message=\"Training report with validation + benchmark results\",\n",
    ")\n",
    "print(f\"📄 Report pushed to HF: {ADAPTER_REPO}/results/report.json\")\n",
    "\n",
    "# ─── Print summary ────────────────────────────────────────\n",
    "print(\"\\n\" + \"=\"*60)\n",
    "print(\"📋 TRAINING SUMMARY\")\n",
    "print(\"=\"*60)\n",
    "print(f\"Model:    {BASE_MODEL}\")\n",
    "print(f\"Dataset:  {DATASET_ID}\")\n",
    "print(f\"Samples:  {REPORT['training'].get('train_samples','?')} train / {REPORT['training'].get('eval_samples','?')} eval\")\n",
    "print(f\"Loss:     train={REPORT['training'].get('final_train_loss','?'):.4f} / eval best={REPORT['training'].get('best_eval_loss','?'):.4f}\")\n",
    "val_passed = sum(1 for r in REPORT['validation'] if r['passed'])\n",
    "val_total = len(REPORT['validation'])\n",
    "print(f\"Val:      {val_passed}/{val_total} passed\")\n",
    "bm_passed = sum(1 for r in REPORT['benchmark'] if r['passed'])\n",
    "bm_total = len(REPORT['benchmark'])\n",
    "print(f\"Bench:    {bm_passed}/{bm_total} passed\")\n",
    "print(f\"Adapter:  https://huggingface.co/{ADAPTER_REPO}\")\n",
    "if REPORT.get('push_merged_url'):\n",
    "    print(f\"Merged:   {REPORT['push_merged_url']}\")\n",
    "print(\"\\n✅ Pipeline complete!\")\n",
    "print(\"=\"*60)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.10.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}