kristiannordby commited on
Commit
fd95545
·
verified ·
1 Parent(s): 1786281

Upload QLORAsqlFinetune (1).ipynb

Browse files
Files changed (1) hide show
  1. QLORAsqlFinetune (1).ipynb +620 -0
QLORAsqlFinetune (1).ipynb ADDED
@@ -0,0 +1,620 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "5d69bd30-a4a5-47da-a1ce-b6f9f228b42c",
7
+ "metadata": {},
8
+ "outputs": [
9
+ {
10
+ "name": "stdout",
11
+ "output_type": "stream",
12
+ "text": [
13
+ "\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",
14
+ "\u001b[0m\n",
15
+ "\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",
16
+ "\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",
17
+ "\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",
18
+ "\u001b[0m\n",
19
+ "\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",
20
+ "\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"
21
+ ]
22
+ }
23
+ ],
24
+ "source": [
25
+ "!pip install -q git+https://github.com/huggingface/transformers.git\n",
26
+ "!pip install -q accelerate datasets peft bitsandbytes"
27
+ ]
28
+ },
29
+ {
30
+ "cell_type": "code",
31
+ "execution_count": 2,
32
+ "id": "33d7d8f7-a2bd-4548-ac7f-45eba6ca1651",
33
+ "metadata": {},
34
+ "outputs": [],
35
+ "source": [
36
+ "import torch\n",
37
+ "from datasets import load_dataset, Dataset\n",
38
+ "from transformers import AutoTokenizer, LlamaForCausalLM, BitsAndBytesConfig, HfArgumentParser, TrainingArguments, Trainer\n",
39
+ "\n",
40
+ "from peft import prepare_model_for_kbit_training, LoraConfig, get_peft_model"
41
+ ]
42
+ },
43
+ {
44
+ "cell_type": "code",
45
+ "execution_count": 22,
46
+ "id": "511a7b95-1089-4312-bc4a-40c843ea60f7",
47
+ "metadata": {},
48
+ "outputs": [
49
+ {
50
+ "data": {
51
+ "application/vnd.jupyter.widget-view+json": {
52
+ "model_id": "ff0282efda104833bda1b818ebd5b4e0",
53
+ "version_major": 2,
54
+ "version_minor": 0
55
+ },
56
+ "text/plain": [
57
+ "Loading checkpoint shards: 0%| | 0/4 [00:00<?, ?it/s]"
58
+ ]
59
+ },
60
+ "metadata": {},
61
+ "output_type": "display_data"
62
+ },
63
+ {
64
+ "name": "stderr",
65
+ "output_type": "stream",
66
+ "text": [
67
+ "/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",
68
+ " warnings.warn(\n",
69
+ "/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",
70
+ " warnings.warn(\n"
71
+ ]
72
+ }
73
+ ],
74
+ "source": [
75
+ "bnb_config = BitsAndBytesConfig(\n",
76
+ " load_in_4bit=True,\n",
77
+ " bnb_4bit_quant_type=\"nf4\",\n",
78
+ " bnb_4bit_compute_dtype=torch.float16\n",
79
+ " )\n",
80
+ "config = LoraConfig(\n",
81
+ " r=8,\n",
82
+ " lora_alpha=16,\n",
83
+ " target_modules=[\"q_proj\",\"k_proj\",\"v_proj\"],\n",
84
+ " lora_dropout=0.1,\n",
85
+ " bias=\"none\",\n",
86
+ " task_type=\"CAUSAL_LM\"\n",
87
+ ")\n",
88
+ "\n",
89
+ "model_name = \"defog/llama-3-sqlcoder-8b\"\n",
90
+ "tokenizer = AutoTokenizer.from_pretrained(model_name)\n",
91
+ "model = LlamaForCausalLM.from_pretrained(model_name, device_map = \"cuda:0\", torch_dtype=torch.float16, quantization_config = bnb_config)"
92
+ ]
93
+ },
94
+ {
95
+ "cell_type": "code",
96
+ "execution_count": 23,
97
+ "id": "007a61b1",
98
+ "metadata": {},
99
+ "outputs": [
100
+ {
101
+ "name": "stdout",
102
+ "output_type": "stream",
103
+ "text": [
104
+ "trainable params: 4,718,592 || all params: 8,034,979,840 || trainable%: 0.0587\n"
105
+ ]
106
+ }
107
+ ],
108
+ "source": [
109
+ "model = get_peft_model(model,config)\n",
110
+ "model.to(\"cuda\")\n",
111
+ "model.print_trainable_parameters()"
112
+ ]
113
+ },
114
+ {
115
+ "cell_type": "code",
116
+ "execution_count": 12,
117
+ "id": "9db5b34f-0223-4bc6-ab23-bc960a0a7b5c",
118
+ "metadata": {},
119
+ "outputs": [
120
+ {
121
+ "data": {
122
+ "application/vnd.jupyter.widget-view+json": {
123
+ "model_id": "e027282bdd2e4f059227ae4f523d19da",
124
+ "version_major": 2,
125
+ "version_minor": 0
126
+ },
127
+ "text/plain": [
128
+ "Map: 0%| | 0/121 [00:00<?, ? examples/s]"
129
+ ]
130
+ },
131
+ "metadata": {},
132
+ "output_type": "display_data"
133
+ }
134
+ ],
135
+ "source": [
136
+ "tokenizer.pad_token = tokenizer.eos_token\n",
137
+ "\n",
138
+ "import json\n",
139
+ "with open(\"syntheticDbData.json\",\"r\") as f:\n",
140
+ " data = json.load(f)\n",
141
+ "untokenized_dataset = Dataset.from_list(data)\n",
142
+ "\n",
143
+ "def preprocess_function(examples):\n",
144
+ " inputs = tokenizer(examples[\"question\"], padding=\"max_length\", truncation=True, max_length=512)\n",
145
+ " labels = tokenizer(examples[\"query\"], padding=\"max_length\", truncation=True, max_length=512)\n",
146
+ " labels[\"input_ids\"] = [-100 if token == tokenizer.pad_token_id else token for token in labels[\"input_ids\"]]\n",
147
+ " return {\"input_ids\": inputs[\"input_ids\"], \"attention_mask\": inputs[\"attention_mask\"], \"labels\": labels[\"input_ids\"]}\n",
148
+ "\n",
149
+ "ds = untokenized_dataset.map(preprocess_function, batched=True)\n",
150
+ "ds = ds.train_test_split(test_size=0.1)"
151
+ ]
152
+ },
153
+ {
154
+ "cell_type": "code",
155
+ "execution_count": 31,
156
+ "id": "f5aabff0-e5e5-41bd-b566-d56e627a30ed",
157
+ "metadata": {},
158
+ "outputs": [
159
+ {
160
+ "data": {
161
+ "text/plain": [
162
+ "DatasetDict({\n",
163
+ " train: Dataset({\n",
164
+ " features: ['question', 'query', 'input_ids', 'attention_mask', 'labels'],\n",
165
+ " num_rows: 108\n",
166
+ " })\n",
167
+ " test: Dataset({\n",
168
+ " features: ['question', 'query', 'input_ids', 'attention_mask', 'labels'],\n",
169
+ " num_rows: 13\n",
170
+ " })\n",
171
+ "})"
172
+ ]
173
+ },
174
+ "execution_count": 31,
175
+ "metadata": {},
176
+ "output_type": "execute_result"
177
+ }
178
+ ],
179
+ "source": [
180
+ "ds"
181
+ ]
182
+ },
183
+ {
184
+ "cell_type": "code",
185
+ "execution_count": 7,
186
+ "id": "53892a58-2582-4611-892f-e2bc7bcf0f2e",
187
+ "metadata": {},
188
+ "outputs": [],
189
+ "source": [
190
+ "prompt_template = lambda user_query: f\"\"\"\n",
191
+ "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n",
192
+ "\n",
193
+ "Generate a SQL query to answer this question: `{user_query}`\n",
194
+ "if the question cannot be answered given the database schema, return \"I do not know\"\n",
195
+ "\n",
196
+ "DDL statements:\n",
197
+ "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",
198
+ "\n",
199
+ "The following SQL query best answers the question `{user_query}`:\n",
200
+ "```sql\n",
201
+ "\"\"\""
202
+ ]
203
+ },
204
+ {
205
+ "cell_type": "code",
206
+ "execution_count": 8,
207
+ "id": "a0197d96",
208
+ "metadata": {},
209
+ "outputs": [
210
+ {
211
+ "name": "stderr",
212
+ "output_type": "stream",
213
+ "text": [
214
+ "Setting `pad_token_id` to `eos_token_id`:None for open-end generation.\n"
215
+ ]
216
+ },
217
+ {
218
+ "name": "stdout",
219
+ "output_type": "stream",
220
+ "text": [
221
+ "Generated SQL: \n",
222
+ "user\n",
223
+ "\n",
224
+ "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",
225
+ "if the question cannot be answered given the database schema, return \"I do not know\"\n",
226
+ "\n",
227
+ "DDL statements:\n",
228
+ "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",
229
+ "\n",
230
+ "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",
231
+ "```sql\n",
232
+ "assistant`\n",
233
+ "\n",
234
+ "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",
235
+ "\n",
236
+ "Hello! I'm your AI Assistant. How can i assist you today?\n",
237
+ "\n",
238
+ "Please feel free share what's on mind or ask me any questions if need help with anything specific.\n",
239
+ "\n",
240
+ "If we're just chatting for fun - that works too!\n",
241
+ "\n",
242
+ "What would like talk about/ask assistance in regards of:\n",
243
+ "\n",
244
+ "1- General knowledge topics.\n",
245
+ "3-General chat/conversation/socializing).\n",
246
+ "4-Helping hands/task management/workflow organization). \n",
247
+ "6-Mental health/wellness/self-care).\n",
248
+ "\n",
249
+ "Let us have some nice conversation together! \n",
250
+ "\n",
251
+ "Choose\n"
252
+ ]
253
+ }
254
+ ],
255
+ "source": [
256
+ "import torch\n",
257
+ "\n",
258
+ "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",
259
+ "\n",
260
+ "input = prompt_template(question)\n",
261
+ "\n",
262
+ "inputs = tokenizer(input, return_tensors=\"pt\", padding=\"max_length\", truncation=True, max_length=512).to(\"cuda\")\n",
263
+ "\n",
264
+ "model.eval()\n",
265
+ "\n",
266
+ "with torch.no_grad():\n",
267
+ " generated_ids = model.generate(\n",
268
+ " input_ids=inputs[\"input_ids\"],\n",
269
+ " attention_mask=inputs[\"attention_mask\"],\n",
270
+ " max_new_tokens=200, # Allow for sufficient token generation\n",
271
+ " repetition_penalty=2.0,\n",
272
+ " early_stopping=True,\n",
273
+ " eos_token_id=tokenizer.eos_token_id, # Use greedy decoding for deterministic output\n",
274
+ " )\n",
275
+ "\n",
276
+ "\n",
277
+ "generated_sql_query = tokenizer.decode(generated_ids[0], skip_special_tokens=True)\n",
278
+ "print(f\"Generated SQL: {generated_sql_query}\")"
279
+ ]
280
+ },
281
+ {
282
+ "cell_type": "code",
283
+ "execution_count": 26,
284
+ "id": "b2d84b8a",
285
+ "metadata": {},
286
+ "outputs": [],
287
+ "source": [
288
+ "from typing import List, Dict, Any\n",
289
+ "\n",
290
+ "class MyDataCollator:\n",
291
+ " def __init__(self, tokenizer=tokenizer, max_length: int = 512):\n",
292
+ " self.tokenizer = tokenizer\n",
293
+ " self.max_length = max_length\n",
294
+ " if self.tokenizer.pad_token is None:\n",
295
+ " self.tokenizer.pad_token = self.tokenizer.eos_token\n",
296
+ "\n",
297
+ " def __call__(self, batch: List[Dict[str, Any]]) -> Dict[str, torch.Tensor]:\n",
298
+ " questions = [prompt_template(item['question']) for item in batch]\n",
299
+ " queries = [item['query'] for item in batch]\n",
300
+ " # Tokenize the queries (labels) first\n",
301
+ " labels = self.tokenizer(queries,padding=\"longest\",truncation=True,max_length=self.max_length,return_tensors=\"pt\")\n",
302
+ " max_label_length = labels['input_ids'].size(1) # Length of labels is longer than length of questions, so I had to pad 'backwards'.\n",
303
+ " inputs = self.tokenizer(questions,padding=\"max_length\",truncation=True,max_length=max_label_length,return_tensors=\"pt\")\n",
304
+ " \n",
305
+ "\n",
306
+ " labels[\"input_ids\"][labels[\"input_ids\"] == self.tokenizer.pad_token_id] = -100\n",
307
+ "\n",
308
+ " return {\"input_ids\": inputs[\"input_ids\"],\"attention_mask\": inputs[\"attention_mask\"],\"labels\": labels[\"input_ids\"]}\n"
309
+ ]
310
+ },
311
+ {
312
+ "cell_type": "code",
313
+ "execution_count": 38,
314
+ "id": "874b4e13-9faf-4c5b-8abc-908ae2c856fb",
315
+ "metadata": {},
316
+ "outputs": [
317
+ {
318
+ "name": "stderr",
319
+ "output_type": "stream",
320
+ "text": [
321
+ "/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",
322
+ " warnings.warn(\n",
323
+ "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"
324
+ ]
325
+ }
326
+ ],
327
+ "source": [
328
+ "from transformers import Trainer, TrainingArguments, EarlyStoppingCallback\n",
329
+ "\n",
330
+ "# Define TrainingArguments\n",
331
+ "training_args = TrainingArguments(\n",
332
+ " output_dir=\"./results\",\n",
333
+ " per_device_train_batch_size=2, \n",
334
+ " gradient_accumulation_steps=8, \n",
335
+ " evaluation_strategy=\"steps\", # Evaluate frequently to monitor overfitting\n",
336
+ " eval_steps=10, \n",
337
+ " num_train_epochs=50, # Train for more epochs but monitor early stopping\n",
338
+ " learning_rate=5e-5, # Lower learning rate for more gradual updates\n",
339
+ " weight_decay=0.01, \n",
340
+ " save_total_limit=2, \n",
341
+ " save_steps=10, \n",
342
+ " logging_steps=5, \n",
343
+ " load_best_model_at_end=True, \n",
344
+ " 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",
345
+ " fp16=True, # Mixed precision to save memory\n",
346
+ " warmup_steps=50, \n",
347
+ " logging_dir=\"./logs\", \n",
348
+ ")\n",
349
+ "\n",
350
+ "# Early stopping callback\n",
351
+ "early_stopping = EarlyStoppingCallback(\n",
352
+ " early_stopping_patience=3 # Stop if validation performance doesn't improve for 3 evals\n",
353
+ ")\n",
354
+ "\n",
355
+ "# Initialize the Trainer with early stopping\n",
356
+ "trainer = Trainer(\n",
357
+ " model=model, # Your model\n",
358
+ " args=training_args, # Training arguments\n",
359
+ " train_dataset=ds['train'], # Your training dataset\n",
360
+ " eval_dataset=ds['train'], # Your validation dataset\n",
361
+ " tokenizer=tokenizer, # Tokenizer\n",
362
+ " data_collator = MyDataCollator(),\n",
363
+ " callbacks=[early_stopping] # Use early stopping to avoid overfitting\n",
364
+ ")"
365
+ ]
366
+ },
367
+ {
368
+ "cell_type": "code",
369
+ "execution_count": 39,
370
+ "id": "902871db-c14d-4128-be80-7b4a661c0b0a",
371
+ "metadata": {},
372
+ "outputs": [
373
+ {
374
+ "name": "stderr",
375
+ "output_type": "stream",
376
+ "text": [
377
+ "/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",
378
+ " warnings.warn('Was asked to gather along dimension 0, but all '\n"
379
+ ]
380
+ },
381
+ {
382
+ "data": {
383
+ "text/html": [
384
+ "\n",
385
+ " <div>\n",
386
+ " \n",
387
+ " <progress value='50' max='50' style='width:300px; height:20px; vertical-align: middle;'></progress>\n",
388
+ " [50/50 20:40, Epoch 28/50]\n",
389
+ " </div>\n",
390
+ " <table border=\"1\" class=\"dataframe\">\n",
391
+ " <thead>\n",
392
+ " <tr style=\"text-align: left;\">\n",
393
+ " <th>Step</th>\n",
394
+ " <th>Training Loss</th>\n",
395
+ " <th>Validation Loss</th>\n",
396
+ " </tr>\n",
397
+ " </thead>\n",
398
+ " <tbody>\n",
399
+ " <tr>\n",
400
+ " <td>10</td>\n",
401
+ " <td>7.618800</td>\n",
402
+ " <td>15.949061</td>\n",
403
+ " </tr>\n",
404
+ " <tr>\n",
405
+ " <td>20</td>\n",
406
+ " <td>6.595500</td>\n",
407
+ " <td>15.314895</td>\n",
408
+ " </tr>\n",
409
+ " <tr>\n",
410
+ " <td>30</td>\n",
411
+ " <td>7.998000</td>\n",
412
+ " <td>14.093081</td>\n",
413
+ " </tr>\n",
414
+ " <tr>\n",
415
+ " <td>40</td>\n",
416
+ " <td>6.360000</td>\n",
417
+ " <td>12.085888</td>\n",
418
+ " </tr>\n",
419
+ " <tr>\n",
420
+ " <td>50</td>\n",
421
+ " <td>4.622300</td>\n",
422
+ " <td>9.611723</td>\n",
423
+ " </tr>\n",
424
+ " </tbody>\n",
425
+ "</table><p>"
426
+ ],
427
+ "text/plain": [
428
+ "<IPython.core.display.HTML object>"
429
+ ]
430
+ },
431
+ "metadata": {},
432
+ "output_type": "display_data"
433
+ },
434
+ {
435
+ "name": "stderr",
436
+ "output_type": "stream",
437
+ "text": [
438
+ "/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",
439
+ " warnings.warn('Was asked to gather along dimension 0, but all '\n",
440
+ "/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",
441
+ " warnings.warn('Was asked to gather along dimension 0, but all '\n",
442
+ "/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",
443
+ " warnings.warn('Was asked to gather along dimension 0, but all '\n",
444
+ "/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",
445
+ " warnings.warn('Was asked to gather along dimension 0, but all '\n"
446
+ ]
447
+ },
448
+ {
449
+ "data": {
450
+ "text/plain": [
451
+ "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})"
452
+ ]
453
+ },
454
+ "execution_count": 39,
455
+ "metadata": {},
456
+ "output_type": "execute_result"
457
+ }
458
+ ],
459
+ "source": [
460
+ "trainer.train()"
461
+ ]
462
+ },
463
+ {
464
+ "cell_type": "code",
465
+ "execution_count": 47,
466
+ "id": "c94bfd35-dd4e-4cde-a0ce-7d7dcfc1775c",
467
+ "metadata": {},
468
+ "outputs": [
469
+ {
470
+ "name": "stderr",
471
+ "output_type": "stream",
472
+ "text": [
473
+ "/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",
474
+ " warnings.warn(\n",
475
+ "/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",
476
+ " warnings.warn(\n",
477
+ "Setting `pad_token_id` to `eos_token_id`:None for open-end generation.\n"
478
+ ]
479
+ },
480
+ {
481
+ "name": "stdout",
482
+ "output_type": "stream",
483
+ "text": [
484
+ "Generated SQL: \n",
485
+ "user\n",
486
+ "\n",
487
+ "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",
488
+ "if the question cannot be answered given the database schema, return \"I do not know\"\n",
489
+ "\n",
490
+ "DDL statements:\n",
491
+ "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",
492
+ "\n",
493
+ "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",
494
+ "```sql\n",
495
+ "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",
496
+ "\n",
497
+ "What is your favorite type of music?\n",
498
+ " - 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",
499
+ " , there are so m...\n",
500
+ " 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"
501
+ ]
502
+ }
503
+ ],
504
+ "source": [
505
+ "import torch\n",
506
+ "\n",
507
+ "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",
508
+ "expected_sql_query = \"\"\"\n",
509
+ "SELECT make, model, mpg, totalMiles \n",
510
+ "FROM cars \n",
511
+ "WHERE modelYear = 2015 \n",
512
+ "AND sellPrice > 30000 \n",
513
+ "ORDER BY mpg DESC \n",
514
+ "LIMIT 1;\n",
515
+ "\"\"\"\n",
516
+ "\n",
517
+ "inputs = tokenizer(prompt_template(question), return_tensors=\"pt\", padding=\"max_length\", truncation=True, max_length=512).to(\"cuda\")\n",
518
+ "\n",
519
+ "model.eval()\n",
520
+ "\n",
521
+ "with torch.no_grad():\n",
522
+ " generated_ids = model.generate(\n",
523
+ " input_ids=inputs[\"input_ids\"],\n",
524
+ " attention_mask=inputs[\"attention_mask\"],\n",
525
+ " max_new_tokens=200, # Allow for sufficient token generation\n",
526
+ " repetition_penalty=2.0,\n",
527
+ " early_stopping=True,\n",
528
+ " eos_token_id=tokenizer.eos_token_id, # Use greedy decoding for deterministic output\n",
529
+ " )\n",
530
+ "\n",
531
+ "\n",
532
+ "generated_sql_query = tokenizer.decode(generated_ids[0], skip_special_tokens=True)\n",
533
+ "print(f\"Generated SQL: {generated_sql_query}\")"
534
+ ]
535
+ },
536
+ {
537
+ "cell_type": "code",
538
+ "execution_count": 44,
539
+ "id": "f6ac37df-0d98-42db-82e4-31aeb1d57baa",
540
+ "metadata": {},
541
+ "outputs": [
542
+ {
543
+ "data": {
544
+ "application/vnd.jupyter.widget-view+json": {
545
+ "model_id": "bc06e356f5cc4b5195787cf465ed589f",
546
+ "version_major": 2,
547
+ "version_minor": 0
548
+ },
549
+ "text/plain": [
550
+ "VBox(children=(HTML(value='<center> <img\\nsrc=https://huggingface.co/front/assets/huggingface_logo-noborder.sv…"
551
+ ]
552
+ },
553
+ "metadata": {},
554
+ "output_type": "display_data"
555
+ }
556
+ ],
557
+ "source": [
558
+ "from huggingface_hub import login\n",
559
+ "login()"
560
+ ]
561
+ },
562
+ {
563
+ "cell_type": "code",
564
+ "execution_count": 46,
565
+ "id": "adfe4f39-093a-46e3-83d9-789106cfe7ea",
566
+ "metadata": {},
567
+ "outputs": [
568
+ {
569
+ "data": {
570
+ "application/vnd.jupyter.widget-view+json": {
571
+ "model_id": "39fc544d3abe4c4e8ecb0a4975557df6",
572
+ "version_major": 2,
573
+ "version_minor": 0
574
+ },
575
+ "text/plain": [
576
+ "adapter_model.safetensors: 0%| | 0.00/18.9M [00:00<?, ?B/s]"
577
+ ]
578
+ },
579
+ "metadata": {},
580
+ "output_type": "display_data"
581
+ },
582
+ {
583
+ "data": {
584
+ "text/plain": [
585
+ "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)"
586
+ ]
587
+ },
588
+ "execution_count": 46,
589
+ "metadata": {},
590
+ "output_type": "execute_result"
591
+ }
592
+ ],
593
+ "source": [
594
+ "model.push_to_hub(\"QLoRA-text2sql-model\")\n",
595
+ "# tokenizer.push_to_hub(\"./finetuned-sql-model\")"
596
+ ]
597
+ }
598
+ ],
599
+ "metadata": {
600
+ "kernelspec": {
601
+ "display_name": "Python 3 (ipykernel)",
602
+ "language": "python",
603
+ "name": "python3"
604
+ },
605
+ "language_info": {
606
+ "codemirror_mode": {
607
+ "name": "ipython",
608
+ "version": 3
609
+ },
610
+ "file_extension": ".py",
611
+ "mimetype": "text/x-python",
612
+ "name": "python",
613
+ "nbconvert_exporter": "python",
614
+ "pygments_lexer": "ipython3",
615
+ "version": "3.10.12"
616
+ }
617
+ },
618
+ "nbformat": 4,
619
+ "nbformat_minor": 5
620
+ }