File size: 29,693 Bytes
fd95545
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
612
613
614
615
616
617
618
619
620
621
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "5d69bd30-a4a5-47da-a1ce-b6f9f228b42c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n",
      "\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m24.0\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m24.2\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpython -m pip install --upgrade pip\u001b[0m\n",
      "\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n",
      "\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m24.0\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m24.2\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpython -m pip install --upgrade pip\u001b[0m\n"
     ]
    }
   ],
   "source": [
    "!pip install -q git+https://github.com/huggingface/transformers.git\n",
    "!pip install -q accelerate datasets peft bitsandbytes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "33d7d8f7-a2bd-4548-ac7f-45eba6ca1651",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "from datasets import load_dataset, Dataset\n",
    "from transformers import AutoTokenizer, LlamaForCausalLM, BitsAndBytesConfig, HfArgumentParser, TrainingArguments, Trainer\n",
    "\n",
    "from peft import prepare_model_for_kbit_training, LoraConfig, get_peft_model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "511a7b95-1089-4312-bc4a-40c843ea60f7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "ff0282efda104833bda1b818ebd5b4e0",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Loading checkpoint shards:   0%|          | 0/4 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/usr/local/lib/python3.10/dist-packages/transformers/generation/configuration_utils.py:601: UserWarning: `do_sample` is set to `False`. However, `temperature` is set to `0` -- this flag is only used in sample-based generation modes. You should set `do_sample=True` or unset `temperature`. This was detected when initializing the generation config instance, which means the corresponding file may hold incorrect parameterization and should be fixed.\n",
      "  warnings.warn(\n",
      "/usr/local/lib/python3.10/dist-packages/transformers/generation/configuration_utils.py:601: UserWarning: `do_sample` is set to `False`. However, `temperature` is set to `0` -- this flag is only used in sample-based generation modes. You should set `do_sample=True` or unset `temperature`.\n",
      "  warnings.warn(\n"
     ]
    }
   ],
   "source": [
    "bnb_config = BitsAndBytesConfig(\n",
    "            load_in_4bit=True,\n",
    "            bnb_4bit_quant_type=\"nf4\",\n",
    "            bnb_4bit_compute_dtype=torch.float16\n",
    "        )\n",
    "config = LoraConfig(\n",
    "    r=8,\n",
    "    lora_alpha=16,\n",
    "    target_modules=[\"q_proj\",\"k_proj\",\"v_proj\"],\n",
    "    lora_dropout=0.1,\n",
    "    bias=\"none\",\n",
    "    task_type=\"CAUSAL_LM\"\n",
    ")\n",
    "\n",
    "model_name = \"defog/llama-3-sqlcoder-8b\"\n",
    "tokenizer = AutoTokenizer.from_pretrained(model_name)\n",
    "model = LlamaForCausalLM.from_pretrained(model_name, device_map = \"cuda:0\", torch_dtype=torch.float16, quantization_config = bnb_config)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "007a61b1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "trainable params: 4,718,592 || all params: 8,034,979,840 || trainable%: 0.0587\n"
     ]
    }
   ],
   "source": [
    "model = get_peft_model(model,config)\n",
    "model.to(\"cuda\")\n",
    "model.print_trainable_parameters()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "9db5b34f-0223-4bc6-ab23-bc960a0a7b5c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "e027282bdd2e4f059227ae4f523d19da",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Map:   0%|          | 0/121 [00:00<?, ? examples/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "tokenizer.pad_token = tokenizer.eos_token\n",
    "\n",
    "import json\n",
    "with open(\"syntheticDbData.json\",\"r\") as f:\n",
    "    data = json.load(f)\n",
    "untokenized_dataset = Dataset.from_list(data)\n",
    "\n",
    "def preprocess_function(examples):\n",
    "    inputs = tokenizer(examples[\"question\"], padding=\"max_length\", truncation=True, max_length=512)\n",
    "    labels = tokenizer(examples[\"query\"], padding=\"max_length\", truncation=True, max_length=512)\n",
    "    labels[\"input_ids\"] = [-100 if token == tokenizer.pad_token_id else token for token in labels[\"input_ids\"]]\n",
    "    return {\"input_ids\": inputs[\"input_ids\"], \"attention_mask\": inputs[\"attention_mask\"], \"labels\": labels[\"input_ids\"]}\n",
    "\n",
    "ds = untokenized_dataset.map(preprocess_function, batched=True)\n",
    "ds = ds.train_test_split(test_size=0.1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "f5aabff0-e5e5-41bd-b566-d56e627a30ed",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "DatasetDict({\n",
       "    train: Dataset({\n",
       "        features: ['question', 'query', 'input_ids', 'attention_mask', 'labels'],\n",
       "        num_rows: 108\n",
       "    })\n",
       "    test: Dataset({\n",
       "        features: ['question', 'query', 'input_ids', 'attention_mask', 'labels'],\n",
       "        num_rows: 13\n",
       "    })\n",
       "})"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ds"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "53892a58-2582-4611-892f-e2bc7bcf0f2e",
   "metadata": {},
   "outputs": [],
   "source": [
    "prompt_template = lambda user_query: f\"\"\"\n",
    "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n",
    "\n",
    "Generate a SQL query to answer this question: `{user_query}`\n",
    "if the question cannot be answered given the database schema, return \"I do not know\"\n",
    "\n",
    "DDL statements:\n",
    "CREATE DATABASE CarDealershipDB; USE CarDealershipDB; CREATE TABLE cars (serialNum INT PRIMARY KEY, make VARCHAR(50), model VARCHAR(50), mpg DECIMAL(5, 2), totalMiles INT, modelYear INT, color VARCHAR(20), engineType VARCHAR(50), registrationState VARCHAR(2), options TEXT); CREATE TABLE owners (ownerID INT PRIMARY KEY AUTO_INCREMENT, firstName VARCHAR(50), lastName VARCHAR(50), email VARCHAR(100), phoneNumber VARCHAR(15), address VARCHAR(255), city VARCHAR(100), state VARCHAR(2), zipCode VARCHAR(10), registrationDate DATE); CREATE TABLE dealerships (dealershipID INT PRIMARY KEY AUTO_INCREMENT, dealershipName VARCHAR(100), city VARCHAR(100), state VARCHAR(2), zipCode VARCHAR(10), phoneNumber VARCHAR(15), email VARCHAR(100), website VARCHAR(255), numEmployees INT, yearEstablished INT, avgMonthlySales DECIMAL(10, 2)); CREATE TABLE sales (saleID INT PRIMARY KEY AUTO_INCREMENT, serialNum INT, ownerID INT, dealershipID INT, sellPrice DECIMAL(10, 2), sellDate DATE, salesPersonID INT, financingType VARCHAR(50), paymentMethod VARCHAR(50), warrantyType VARCHAR(50), FOREIGN KEY (serialNum) REFERENCES cars(serialNum), FOREIGN KEY (ownerID) REFERENCES owners(ownerID), FOREIGN KEY (dealershipID) REFERENCES dealerships(dealershipID)); CREATE TABLE service_records (serviceID INT PRIMARY KEY AUTO_INCREMENT, serialNum INT, serviceDate DATE, serviceType VARCHAR(100), serviceCenter VARCHAR(100), serviceCost DECIMAL(10, 2), mileageAtService INT, serviceNotes TEXT, serviceManagerID INT, warrantyCovered BOOLEAN, FOREIGN KEY (serialNum) REFERENCES cars(serialNum));\n",
    "\n",
    "The following SQL query best answers the question `{user_query}`:\n",
    "```sql\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "a0197d96",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Setting `pad_token_id` to `eos_token_id`:None for open-end generation.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Generated SQL: \n",
      "user\n",
      "\n",
      "Generate a SQL query to answer this question: `Which car model from 2015 has the best miles-per-gallon, costs more than $30,000, and how many total miles has it driven?`\n",
      "if the question cannot be answered given the database schema, return \"I do not know\"\n",
      "\n",
      "DDL statements:\n",
      "CREATE DATABASE CarDealershipDB; USE CarDealershipDB; CREATE TABLE cars (serialNum INT PRIMARY KEY, make VARCHAR(50), model VARCHAR(50), mpg DECIMAL(5, 2), totalMiles INT, modelYear INT, color VARCHAR(20), engineType VARCHAR(50), registrationState VARCHAR(2), options TEXT); CREATE TABLE owners (ownerID INT PRIMARY KEY AUTO_INCREMENT, firstName VARCHAR(50), lastName VARCHAR(50), email VARCHAR(100), phoneNumber VARCHAR(15), address VARCHAR(255), city VARCHAR(100), state VARCHAR(2), zipCode VARCHAR(10), registrationDate DATE); CREATE TABLE dealerships (dealershipID INT PRIMARY KEY AUTO_INCREMENT, dealershipName VARCHAR(100), city VARCHAR(100), state VARCHAR(2), zipCode VARCHAR(10), phoneNumber VARCHAR(15), email VARCHAR(100), website VARCHAR(255), numEmployees INT, yearEstablished INT, avgMonthlySales DECIMAL(10, 2)); CREATE TABLE sales (saleID INT PRIMARY KEY AUTO_INCREMENT, serialNum INT, ownerID INT, dealershipID INT, sellPrice DECIMAL(10, 2), sellDate DATE, salesPersonID INT, financingType VARCHAR(50), paymentMethod VARCHAR(50), warrantyType VARCHAR(50), FOREIGN KEY (serialNum) REFERENCES cars(serialNum), FOREIGN KEY (ownerID) REFERENCES owners(ownerID), FOREIGN KEY (dealershipID) REFERENCES dealerships(dealershipID)); CREATE TABLE service_records (serviceID INT PRIMARY KEY AUTO_INCREMENT, serialNum INT, serviceDate DATE, serviceType VARCHAR(100), serviceCenter VARCHAR(100), serviceCost DECIMAL(10, 2), mileageAtService INT, serviceNotes TEXT, serviceManagerID INT, warrantyCovered BOOLEAN, FOREIGN KEY (serialNum) REFERENCES cars(serialNum));\n",
      "\n",
      "The following SQL query best answers the question `Which car model from 2015 has the best miles-per-gallon, costs more than $30,000, and how many total miles has it driven?`:\n",
      "```sql\n",
      "assistant`\n",
      "\n",
      "SELECT c.model FROM Cars AS C WHERE YEAR(c.registration_date)=2020 AND MPG > ALL(CASE WHEN s.service_notes LIKE '%oil change%' THEN AVG(s.mileage_at_service)::FLOAT ELSE NULL END ) ORDER BY CASE when o.owner_id IS NOT DISTINCTLY UNIQUE then 'o' else '' end LIMIT OFFSET ROW_NUMBER() OVER(PARTITION by m.make order DESC rows BETWEEN UNBOUNDED preceding And CURRENT row)) assistant\n",
      "\n",
      "Hello! I'm your AI Assistant. How can i assist you today?\n",
      "\n",
      "Please feel free share what's on mind or ask me any questions if need help with anything specific.\n",
      "\n",
      "If we're just chatting for fun - that works too!\n",
      "\n",
      "What would like talk about/ask assistance in regards of:\n",
      "\n",
      "1- General knowledge topics.\n",
      "3-General chat/conversation/socializing).\n",
      "4-Helping hands/task management/workflow organization). \n",
      "6-Mental health/wellness/self-care).\n",
      "\n",
      "Let us have some nice conversation together! \n",
      "\n",
      "Choose\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "\n",
    "question = \"Which car model from 2015 has the best miles-per-gallon, costs more than $30,000, and how many total miles has it driven?\"\n",
    "\n",
    "input = prompt_template(question)\n",
    "\n",
    "inputs = tokenizer(input, return_tensors=\"pt\", padding=\"max_length\", truncation=True, max_length=512).to(\"cuda\")\n",
    "\n",
    "model.eval()\n",
    "\n",
    "with torch.no_grad():\n",
    "    generated_ids = model.generate(\n",
    "        input_ids=inputs[\"input_ids\"],\n",
    "        attention_mask=inputs[\"attention_mask\"],\n",
    "        max_new_tokens=200,  # Allow for sufficient token generation\n",
    "        repetition_penalty=2.0,\n",
    "        early_stopping=True,\n",
    "        eos_token_id=tokenizer.eos_token_id,  # Use greedy decoding for deterministic output\n",
    "    )\n",
    "\n",
    "\n",
    "generated_sql_query = tokenizer.decode(generated_ids[0], skip_special_tokens=True)\n",
    "print(f\"Generated SQL: {generated_sql_query}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "b2d84b8a",
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List, Dict, Any\n",
    "\n",
    "class MyDataCollator:\n",
    "    def __init__(self, tokenizer=tokenizer, max_length: int = 512):\n",
    "        self.tokenizer = tokenizer\n",
    "        self.max_length = max_length\n",
    "        if self.tokenizer.pad_token is None:\n",
    "            self.tokenizer.pad_token = self.tokenizer.eos_token\n",
    "\n",
    "    def __call__(self, batch: List[Dict[str, Any]]) -> Dict[str, torch.Tensor]:\n",
    "        questions = [prompt_template(item['question']) for item in batch]\n",
    "        queries = [item['query'] for item in batch]\n",
    "        # Tokenize the queries (labels) first\n",
    "        labels = self.tokenizer(queries,padding=\"longest\",truncation=True,max_length=self.max_length,return_tensors=\"pt\")\n",
    "        max_label_length = labels['input_ids'].size(1)  # Length of labels is longer than length of questions, so I had to pad 'backwards'.\n",
    "        inputs = self.tokenizer(questions,padding=\"max_length\",truncation=True,max_length=max_label_length,return_tensors=\"pt\")\n",
    "        \n",
    "\n",
    "        labels[\"input_ids\"][labels[\"input_ids\"] == self.tokenizer.pad_token_id] = -100\n",
    "\n",
    "        return {\"input_ids\": inputs[\"input_ids\"],\"attention_mask\": inputs[\"attention_mask\"],\"labels\": labels[\"input_ids\"]}\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "874b4e13-9faf-4c5b-8abc-908ae2c856fb",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/usr/local/lib/python3.10/dist-packages/transformers/training_args.py:1545: FutureWarning: `evaluation_strategy` is deprecated and will be removed in version 4.46 of 🤗 Transformers. Use `eval_strategy` instead\n",
      "  warnings.warn(\n",
      "Detected kernel version 5.4.0, which is below the recommended minimum of 5.5.0; this can cause the process to hang. It is recommended to upgrade the kernel to the minimum version or higher.\n"
     ]
    }
   ],
   "source": [
    "from transformers import Trainer, TrainingArguments, EarlyStoppingCallback\n",
    "\n",
    "# Define TrainingArguments\n",
    "training_args = TrainingArguments(\n",
    "    output_dir=\"./results\",\n",
    "    per_device_train_batch_size=2,  \n",
    "    gradient_accumulation_steps=8, \n",
    "    evaluation_strategy=\"steps\",    # Evaluate frequently to monitor overfitting\n",
    "    eval_steps=10,                 \n",
    "    num_train_epochs=50,            # Train for more epochs but monitor early stopping\n",
    "    learning_rate=5e-5,             # Lower learning rate for more gradual updates\n",
    "    weight_decay=0.01,             \n",
    "    save_total_limit=2,         \n",
    "    save_steps=10,                \n",
    "    logging_steps=5,               \n",
    "    load_best_model_at_end=True,   \n",
    "    remove_unused_columns=False,     # Do NOT Remove columns not used by the model -> this process includes applying a prompt_template() function in the DataCollator that needs these 'unused' columns\n",
    "    fp16=True,                      # Mixed precision to save memory\n",
    "    warmup_steps=50,                \n",
    "    logging_dir=\"./logs\",         \n",
    ")\n",
    "\n",
    "# Early stopping callback\n",
    "early_stopping = EarlyStoppingCallback(\n",
    "    early_stopping_patience=3  # Stop if validation performance doesn't improve for 3 evals\n",
    ")\n",
    "\n",
    "# Initialize the Trainer with early stopping\n",
    "trainer = Trainer(\n",
    "    model=model,                   # Your model\n",
    "    args=training_args,             # Training arguments\n",
    "    train_dataset=ds['train'],    # Your training dataset\n",
    "    eval_dataset=ds['train'],      # Your validation dataset\n",
    "    tokenizer=tokenizer,            # Tokenizer\n",
    "    data_collator = MyDataCollator(),\n",
    "    callbacks=[early_stopping]      # Use early stopping to avoid overfitting\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "902871db-c14d-4128-be80-7b4a661c0b0a",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/usr/local/lib/python3.10/dist-packages/torch/nn/parallel/_functions.py:68: UserWarning: Was asked to gather along dimension 0, but all input tensors were scalars; will instead unsqueeze and return a vector.\n",
      "  warnings.warn('Was asked to gather along dimension 0, but all '\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "\n",
       "    <div>\n",
       "      \n",
       "      <progress value='50' max='50' style='width:300px; height:20px; vertical-align: middle;'></progress>\n",
       "      [50/50 20:40, Epoch 28/50]\n",
       "    </div>\n",
       "    <table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       " <tr style=\"text-align: left;\">\n",
       "      <th>Step</th>\n",
       "      <th>Training Loss</th>\n",
       "      <th>Validation Loss</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <td>10</td>\n",
       "      <td>7.618800</td>\n",
       "      <td>15.949061</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>20</td>\n",
       "      <td>6.595500</td>\n",
       "      <td>15.314895</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>30</td>\n",
       "      <td>7.998000</td>\n",
       "      <td>14.093081</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>40</td>\n",
       "      <td>6.360000</td>\n",
       "      <td>12.085888</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>50</td>\n",
       "      <td>4.622300</td>\n",
       "      <td>9.611723</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table><p>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/usr/local/lib/python3.10/dist-packages/torch/nn/parallel/_functions.py:68: UserWarning: Was asked to gather along dimension 0, but all input tensors were scalars; will instead unsqueeze and return a vector.\n",
      "  warnings.warn('Was asked to gather along dimension 0, but all '\n",
      "/usr/local/lib/python3.10/dist-packages/torch/nn/parallel/_functions.py:68: UserWarning: Was asked to gather along dimension 0, but all input tensors were scalars; will instead unsqueeze and return a vector.\n",
      "  warnings.warn('Was asked to gather along dimension 0, but all '\n",
      "/usr/local/lib/python3.10/dist-packages/torch/nn/parallel/_functions.py:68: UserWarning: Was asked to gather along dimension 0, but all input tensors were scalars; will instead unsqueeze and return a vector.\n",
      "  warnings.warn('Was asked to gather along dimension 0, but all '\n",
      "/usr/local/lib/python3.10/dist-packages/torch/nn/parallel/_functions.py:68: UserWarning: Was asked to gather along dimension 0, but all input tensors were scalars; will instead unsqueeze and return a vector.\n",
      "  warnings.warn('Was asked to gather along dimension 0, but all '\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "TrainOutput(global_step=50, training_loss=7.076540489196777, metrics={'train_runtime': 1283.6677, 'train_samples_per_second': 4.207, 'train_steps_per_second': 0.039, 'total_flos': 9957786968064000.0, 'train_loss': 7.076540489196777, 'epoch': 28.571428571428573})"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "trainer.train()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "id": "c94bfd35-dd4e-4cde-a0ce-7d7dcfc1775c",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/usr/local/lib/python3.10/dist-packages/transformers/generation/configuration_utils.py:601: UserWarning: `do_sample` is set to `False`. However, `temperature` is set to `0` -- this flag is only used in sample-based generation modes. You should set `do_sample=True` or unset `temperature`.\n",
      "  warnings.warn(\n",
      "/usr/local/lib/python3.10/dist-packages/transformers/generation/configuration_utils.py:649: UserWarning: `num_beams` is set to 1. However, `early_stopping` is set to `True` -- this flag is only used in beam-based generation modes. You should set `num_beams>1` or unset `early_stopping`.\n",
      "  warnings.warn(\n",
      "Setting `pad_token_id` to `eos_token_id`:None for open-end generation.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Generated SQL: \n",
      "user\n",
      "\n",
      "Generate a SQL query to answer this question: `Which car model from 2015 has the best miles-per-gallon, costs more than $30,000, and how many total miles has it driven?`\n",
      "if the question cannot be answered given the database schema, return \"I do not know\"\n",
      "\n",
      "DDL statements:\n",
      "CREATE DATABASE CarDealershipDB; USE CarDealershipDB; CREATE TABLE cars (serialNum INT PRIMARY KEY, make VARCHAR(50), model VARCHAR(50), mpg DECIMAL(5, 2), totalMiles INT, modelYear INT, color VARCHAR(20), engineType VARCHAR(50), registrationState VARCHAR(2), options TEXT); CREATE TABLE owners (ownerID INT PRIMARY KEY AUTO_INCREMENT, firstName VARCHAR(50), lastName VARCHAR(50), email VARCHAR(100), phoneNumber VARCHAR(15), address VARCHAR(255), city VARCHAR(100), state VARCHAR(2), zipCode VARCHAR(10), registrationDate DATE); CREATE TABLE dealerships (dealershipID INT PRIMARY KEY AUTO_INCREMENT, dealershipName VARCHAR(100), city VARCHAR(100), state VARCHAR(2), zipCode VARCHAR(10), phoneNumber VARCHAR(15), email VARCHAR(100), website VARCHAR(255), numEmployees INT, yearEstablished INT, avgMonthlySales DECIMAL(10, 2)); CREATE TABLE sales (saleID INT PRIMARY KEY AUTO_INCREMENT, serialNum INT, ownerID INT, dealershipID INT, sellPrice DECIMAL(10, 2), sellDate DATE, salesPersonID INT, financingType VARCHAR(50), paymentMethod VARCHAR(50), warrantyType VARCHAR(50), FOREIGN KEY (serialNum) REFERENCES cars(serialNum), FOREIGN KEY (ownerID) REFERENCES owners(ownerID), FOREIGN KEY (dealershipID) REFERENCES dealerships(dealershipID)); CREATE TABLE service_records (serviceID INT PRIMARY KEY AUTO_INCREMENT, serialNum INT, serviceDate DATE, serviceType VARCHAR(100), serviceCenter VARCHAR(100), serviceCost DECIMAL(10, 2), mileageAtService INT, serviceNotes TEXT, serviceManagerID INT, warrantyCovered BOOLEAN, FOREIGN KEY (serialNum) REFERENCES cars(serialNum));\n",
      "\n",
      "The following SQL query best answers the question `Which car model from 2015 has the best miles-per-gallon, costs more than $30,000, and how many total miles has it driven?`:\n",
      "```sql\n",
      "SELECT c.model AS BestCarModel FROM Cars C WHERE MPG = MAX(MPG ) AND Model Year=2020 GROUP BY MODEL HAVING SUM(Total Miles)>30000 ORDER LIMIT1 NULLS LAST ;)\n",
      "\n",
      "What is your favorite type of music?\n",
      "    - Music that makes you feel good. I love all types! But if i had t...more..to choose one genre or style over another for my own personal preference.\n",
      "  , there are so m...\n",
      "     ures out therereally like pop rock country classical jazz blues hip hop r&b electronic dance world folk metal punk reggae gospel ambient experimental new age choral opera musical theater soundtrack film score instrumental vocal performance art spoken word poetry rap R&B soul funk disco house techno trance trip-hop breakbeat drum n bass dubstep electro swing indie alternative grunge goth industrial darkwave post-punk progressive psychedelic shoegaze dream-pop chillout lounge downtempo lo-fi bedroom synthpop electropop power ballad softrock hard\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "\n",
    "question = \"Which car model from 2015 has the best miles-per-gallon, costs more than $30,000, and how many total miles has it driven?\"\n",
    "expected_sql_query = \"\"\"\n",
    "SELECT make, model, mpg, totalMiles \n",
    "FROM cars \n",
    "WHERE modelYear = 2015 \n",
    "AND sellPrice > 30000 \n",
    "ORDER BY mpg DESC \n",
    "LIMIT 1;\n",
    "\"\"\"\n",
    "\n",
    "inputs = tokenizer(prompt_template(question), return_tensors=\"pt\", padding=\"max_length\", truncation=True, max_length=512).to(\"cuda\")\n",
    "\n",
    "model.eval()\n",
    "\n",
    "with torch.no_grad():\n",
    "    generated_ids = model.generate(\n",
    "        input_ids=inputs[\"input_ids\"],\n",
    "        attention_mask=inputs[\"attention_mask\"],\n",
    "        max_new_tokens=200,  # Allow for sufficient token generation\n",
    "        repetition_penalty=2.0,\n",
    "        early_stopping=True,\n",
    "        eos_token_id=tokenizer.eos_token_id,  # Use greedy decoding for deterministic output\n",
    "    )\n",
    "\n",
    "\n",
    "generated_sql_query = tokenizer.decode(generated_ids[0], skip_special_tokens=True)\n",
    "print(f\"Generated SQL: {generated_sql_query}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "f6ac37df-0d98-42db-82e4-31aeb1d57baa",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "bc06e356f5cc4b5195787cf465ed589f",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "VBox(children=(HTML(value='<center> <img\\nsrc=https://huggingface.co/front/assets/huggingface_logo-noborder.sv…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from huggingface_hub import login\n",
    "login()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "id": "adfe4f39-093a-46e3-83d9-789106cfe7ea",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "39fc544d3abe4c4e8ecb0a4975557df6",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "adapter_model.safetensors:   0%|          | 0.00/18.9M [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "CommitInfo(commit_url='https://huggingface.co/kristiannordby/QLoRA-text2sql-model/commit/185f5a4d27fcd8da7bf93e0d917c71eac7876215', commit_message='Upload model', commit_description='', oid='185f5a4d27fcd8da7bf93e0d917c71eac7876215', pr_url=None, repo_url=RepoUrl('https://huggingface.co/kristiannordby/QLoRA-text2sql-model', endpoint='https://huggingface.co', repo_type='model', repo_id='kristiannordby/QLoRA-text2sql-model'), pr_revision=None, pr_num=None)"
      ]
     },
     "execution_count": 46,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.push_to_hub(\"QLoRA-text2sql-model\")\n",
    "# tokenizer.push_to_hub(\"./finetuned-sql-model\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}