{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Run pre-trained DeepSeek Coder 1.3B Model on Chat-GPT 4o generated dataset" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## First load dataset into pandas dataframe" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Total dataset examples: 1044\n", "\n", "\n", "Which team had the largest lead in a single game in the 2001 season?\n", "SELECT g.team_name_home AS team, os.largest_lead_home AS lead FROM other_stats os JOIN game g ON os.game_id = g.game_id WHERE g.season_id = '22001' ORDER BY os.largest_lead_home DESC LIMIT 1;\n", "Portland Trail Blazers|47\n" ] } ], "source": [ "import pandas as pd \n", "import warnings\n", "warnings.filterwarnings(\"ignore\")\n", "\n", "# Load dataset and check length\n", "df = pd.read_csv(\"./train-data/sql_train.tsv\", sep='\\t')\n", "print(\"Total dataset examples: \" + str(len(df)))\n", "print(\"\\n\")\n", "\n", "# Test sampling\n", "sample = df.sample(n=1)\n", "print(sample[\"natural_query\"].values[0])\n", "print(sample[\"sql_query\"].values[0])\n", "print(sample[\"result\"].values[0])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Load pre-trained DeepSeek model using transformers and pytorch packages" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "from transformers import AutoTokenizer, AutoModelForCausalLM\n", "import torch\n", "\n", "# Set device to cuda if available, otherwise CPU\n", "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", "\n", "# Load model and tokenizer\n", "tokenizer = AutoTokenizer.from_pretrained(\"./deepseek-coder-1.3b-instruct\")\n", "model = AutoModelForCausalLM.from_pretrained(\"./deepseek-coder-1.3b-instruct\", torch_dtype=torch.bfloat16, device_map=device) \n", "model.generation_config.pad_token_id = tokenizer.pad_token_id" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Create prompt to setup the model for better performance" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [], "source": [ "from src.prompts.prompt import input_text" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Test model performance on a single example" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SQLite:\n", "SELECT team_abbreviation_home FROM other_stats WHERE lead_changes = 1 AND season_id = '2001';\n", "\n" ] } ], "source": [ "# Create message with sample query and run model\n", "message=[{ 'role': 'user', 'content': input_text + sample[\"natural_query\"].values[0]}]\n", "inputs = tokenizer.apply_chat_template(message, add_generation_prompt=True, return_tensors=\"pt\").to(model.device)\n", "outputs = model.generate(inputs, max_new_tokens=512, do_sample=False, top_k=50, top_p=0.95, num_return_sequences=1, eos_token_id=tokenizer.eos_token_id)\n", "\n", "# Print output\n", "query_output = tokenizer.decode(outputs[0][len(inputs[0]):], skip_special_tokens=True)\n", "print(query_output)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Test sample output on sqlite3 database" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "cleaned\n" ] } ], "source": [ "import sqlite3 as sql\n", "\n", "# Create connection to sqlite3 database\n", "connection = sql.connect('./nba-data/nba.sqlite')\n", "cursor = connection.cursor()\n", "\n", "# Execute query from model output and print result\n", "if query_output[0:7] == \"SQLite:\":\n", " print(\"cleaned\")\n", " query = query_output[7:]\n", "elif query_output[0:4] == \"SQL:\":\n", " query = query_output[4:]\n", "else:\n", " query = query_output\n", "\n", "try:\n", " cursor.execute(query)\n", " rows = cursor.fetchall()\n", " for row in rows:\n", " print(row)\n", "except:\n", " pass" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Create function to compare output to ground truth result from examples" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "ename": "ImportError", "evalue": "cannot import name 'compare_result_two' from 'src.evaluation.compare_result' (/Users/esteban/Documents/USC/spring_2025/NLP/SQL-Generation/src/evaluation/compare_result.py)", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mImportError\u001b[0m Traceback (most recent call last)", "Cell \u001b[0;32mIn[30], line 2\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[38;5;28;01mimport\u001b[39;00m \u001b[38;5;21;01mmath\u001b[39;00m\n\u001b[0;32m----> 2\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01msrc\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mevaluation\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mcompare_result\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m compare_result_two\n\u001b[1;32m 4\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mcompare_result\u001b[39m(sample_query, sample_result, query_output):\n\u001b[1;32m 5\u001b[0m \u001b[38;5;66;03m# Clean model output to only have the query output\u001b[39;00m\n\u001b[1;32m 6\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m query_output[\u001b[38;5;241m0\u001b[39m:\u001b[38;5;241m7\u001b[39m] \u001b[38;5;241m==\u001b[39m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mSQLite:\u001b[39m\u001b[38;5;124m\"\u001b[39m:\n", "\u001b[0;31mImportError\u001b[0m: cannot import name 'compare_result_two' from 'src.evaluation.compare_result' (/Users/esteban/Documents/USC/spring_2025/NLP/SQL-Generation/src/evaluation/compare_result.py)" ] } ], "source": [ "import math\n", "from src.evaluation.compare_result import compare_result_two\n", "\n", "def compare_result(sample_query, sample_result, query_output):\n", " # Clean model output to only have the query output\n", " if query_output[0:7] == \"SQLite:\":\n", " query = query_output[7:]\n", " elif query_output[0:4] == \"SQL:\":\n", " query = query_output[4:]\n", " else:\n", " query = query_output\n", " \n", " # Try to execute query, if it fails, then this is a failure of the model\n", " try:\n", " # Execute query and obtain result\n", " cursor.execute(query)\n", " rows = cursor.fetchall()\n", "\n", " # Strip all whitespace before comparing queries since there may be differences in spacing, newlines, tabs, etc.\n", " query = query.replace(\" \", \"\").replace(\"\\n\", \"\").replace(\"\\t\", \"\")\n", " sample_query = sample_query.replace(\" \", \"\").replace(\"\\n\", \"\").replace(\"\\t\", \"\")\n", " query_match = (query == sample_query)\n", "\n", " # If the queries match, the results clearly also match\n", " if query_match:\n", " return True, True, True\n", "\n", " # Check if this is a multi-line query\n", " if \"|\" in sample_result or \"(\" in sample_result:\n", " #print(rows)\n", " # Create list of results by stripping separators and splitting on them\n", " if \"(\" in sample_result:\n", " sample_result = sample_result.replace(\"(\", \"\").replace(\")\", \"\")\n", " result_list = sample_result.split(\",\") \n", " else:\n", " result_list = sample_result.split(\"|\") \n", "\n", " # Strip all results in list\n", " for i in range(len(result_list)):\n", " result_list[i] = str(result_list[i]).strip()\n", " \n", " # Loop through model result and see if it matches training example\n", " result = False\n", " for row in rows:\n", " for r in row:\n", " for res in result_list:\n", " try:\n", " if math.isclose(float(r), float(res), abs_tol=0.5):\n", " return True, query_match, True\n", " except:\n", " if r in res or res in r:\n", " return True, query_match, True\n", " \n", " # Check if the model returned a sum of examples as opposed to the whole thing\n", " if len(rows) == 1:\n", " for r in rows[0]:\n", " if r == str(len(result_list)):\n", " return True, query_match, True\n", " \n", " return True, query_match, result\n", " # Else the sample result is a single value or string\n", " else:\n", " #print(rows)\n", " result = False\n", " # Loop through model result and see if it contains the sample result\n", " for row in rows:\n", " for r in row:\n", " # Check by string\n", " if str(r) in str(sample_result):\n", " try:\n", " if math.isclose(float(r), float(sample_result), abs_tol=0.5):\n", " return True, query_match, True\n", " except:\n", " return True, query_match, True\n", " # Check by number, using try incase the cast as float fails\n", " try:\n", " if math.isclose(float(r), float(sample_result), abs_tol=0.5):\n", " return True, query_match, True\n", " except:\n", " pass\n", "\n", " # Check if the model returned a list of examples instead of a total sum (both acceptable)\n", " try:\n", " if len(rows) > 1 and len(rows) == int(sample_result):\n", " return True, query_match, True\n", " if len(rows[0]) > 1 and rows[0][1] is not None and len(rows[0]) == int(sample_result):\n", " return True, query_match, True\n", " except:\n", " pass\n", "\n", " # Compare results and return\n", " return True, query_match, result\n", " except:\n", " return False, False, False\n", "\n", "# Obtain sample\n", "sample = df.sample(n=1)\n", "sample_dic = {\n", " \"natural_query\": \"How many home games did the Miami Heat play in the 2021 season?\",\n", " \"sql_query\": \"SELECT COUNT(*) FROM game WHERE team_name_home = 'Miami Heat' AND season_id = '22021';\",\n", " \"result\": 41.0\n", "}\n", "\n", "sample = pd.DataFrame([sample_dic])\n", "\"\"\"\n", "print(sample[\"natural_query\"].values[0])\n", "print(sample[\"sql_query\"].values[0])\n", "print(sample[\"result\"].values[0])\n", "\"\"\"\n", "\n", "# Create message with sample query and run model\n", "message=[{ 'role': 'user', 'content': input_text + sample[\"natural_query\"].values[0]}]\n", "inputs = tokenizer.apply_chat_template(message, add_generation_prompt=True, return_tensors=\"pt\").to(model.device)\n", "outputs = model.generate(inputs, max_new_tokens=512, do_sample=False, top_k=50, top_p=0.95, num_return_sequences=1, eos_token_id=tokenizer.eos_token_id)\n", "\n", "# Print output\n", "query_output = tokenizer.decode(outputs[0][len(inputs[0]):], skip_special_tokens=True)\n", "print(query_output)\n", "\n", "result = compare_result(sample[\"sql_query\"].values[0], sample[\"result\"].values[0], query_output)\n", "print(\"Statement valid? \" + str(result[0]))\n", "print(\"SQLite matched? \" + str(result[1]))\n", "print(\"Result matched? \" + str(result[2]))\n", "\n", "result_two = compare_result_two(cursor, sample[\"sql_query\"].values[0], sample[\"result\"].values[0], query_output)\n", "print(\"Statement valid? \" + str(result_two[0]))\n", "print(\"SQLite matched? \" + str(result_two[1]))\n", "print(\"Result matched? \" + str(result_two[2]))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Create function to evaluate pretrained model on full datasets" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "def run_evaluation(nba_df, title):\n", " counter = 0\n", " num_valid = 0\n", " num_sql_matched = 0\n", " num_result_matched = 0\n", " for index, row in nba_df.iterrows():\n", " # Create message with sample query and run model\n", " message=[{ 'role': 'user', 'content': input_text + row[\"natural_query\"]}]\n", " inputs = tokenizer.apply_chat_template(message, add_generation_prompt=True, return_tensors=\"pt\").to(model.device)\n", " outputs = model.generate(inputs, max_new_tokens=512, do_sample=False, top_k=50, top_p=0.95, num_return_sequences=1, eos_token_id=tokenizer.eos_token_id)\n", "\n", " # Obtain output\n", " query_output = tokenizer.decode(outputs[0][len(inputs[0]):], skip_special_tokens=True)\n", "\n", " # Evaluate model result\n", " valid, sql_matched, result_matched = compare_result(row[\"sql_query\"], row[\"result\"], query_output)\n", " if valid:\n", " num_valid += 1\n", " if sql_matched:\n", " num_sql_matched += 1\n", " if result_matched:\n", " num_result_matched += 1\n", "\n", " # Break after predefined number of examples\n", " counter += 1\n", " if counter % 50 == 0:\n", " print(\"Completed \" + str(counter))\n", "\n", " # Print evaluation results\n", " print(\"\\n\" + title + \" results:\")\n", " print(\"Percent valid: \" + str(num_valid / len(nba_df)))\n", " print(\"Percent SQLite matched: \" + str(num_sql_matched / len(nba_df)))\n", " print(\"Percent result matched: \" + str(num_result_matched / len(nba_df)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Evaluate on less than 90 dataset" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Completed 50\n", "Completed 100\n", "Completed 150\n", "Completed 200\n", "\n", "Less than 90 results:\n", "Percent valid: 0.8448979591836735\n", "Percent SQLite matched: 0.43673469387755104\n", "Percent result matched: 0.6530612244897959\n", "Dataset length: 245\n" ] } ], "source": [ "less_than_90_df = pd.read_csv(\"./train-data/less_than_90.tsv\", sep='\\t')\n", "run_evaluation(less_than_90_df, \"Less than 90\")\n", "print(\"Dataset length: \" + str(len(less_than_90_df)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Evaluate on game table queries" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Completed 50\n", "Completed 100\n", "Completed 150\n", "Completed 200\n", "Completed 250\n", "Completed 300\n", "Completed 350\n", "Completed 400\n", "Completed 450\n", "Completed 500\n", "Completed 550\n", "Completed 600\n", "Completed 650\n", "Completed 700\n", "Completed 750\n", "Completed 800\n", "\n", "Queries from game results:\n", "Percent valid: 0.7613365155131265\n", "Percent SQLite matched: 0.13842482100238662\n", "Percent result matched: 0.383054892601432\n", "Dataset length: 838\n" ] } ], "source": [ "game_queries = pd.read_csv(\"./train-data/queries_from_game.tsv\", sep='\\t')\n", "run_evaluation(game_queries, \"Queries from game\")\n", "print(\"Dataset length: \" + str(len(game_queries)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Evaluate on other stats queries" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Completed 50\n", "Completed 100\n", "Completed 150\n", "\n", "Queries from other stats results:\n", "Percent valid: 0.21428571428571427\n", "Percent SQLite matched: 0.01948051948051948\n", "Percent result matched: 0.07142857142857142\n", "Dataset length: 154\n" ] } ], "source": [ "other_stats_queries = pd.read_csv(\"./train-data/queries_from_other_stats.tsv\", sep='\\t')\n", "run_evaluation(other_stats_queries, \"Queries from other stats\")\n", "print(\"Dataset length: \" + str(len(other_stats_queries)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Evaluate on team queries" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Completed 50\n", "\n", "Queries from team results:\n", "Percent valid: 0.8653846153846154\n", "Percent SQLite matched: 0.5961538461538461\n", "Percent result matched: 0.7884615384615384\n", "Dataset length: 52\n" ] } ], "source": [ "team_queries = pd.read_csv(\"./train-data/queries_from_team.tsv\", sep='\\t')\n", "run_evaluation(team_queries, \"Queries from team\")\n", "print(\"Dataset length: \" + str(len(team_queries)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Evaluate on queries requiring join statements" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Completed 50\n", "Completed 100\n", "Completed 150\n", "\n", "Queries with join results:\n", "Percent valid: 0.1945945945945946\n", "Percent SQLite matched: 0.0\n", "Percent result matched: 0.04864864864864865\n", "Dataset length: 185\n" ] } ], "source": [ "join_queries = pd.read_csv(\"./train-data/with_join.tsv\", sep='\\t')\n", "run_evaluation(join_queries, \"Queries with join\")\n", "print(\"Dataset length: \" + str(len(join_queries)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Evaluate on queries not requiring join statements" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Completed 50\n", "Completed 100\n", "Completed 150\n", "Completed 200\n", "Completed 250\n", "Completed 300\n", "Completed 350\n", "Completed 400\n", "Completed 450\n", "Completed 500\n", "Completed 550\n", "Completed 600\n", "Completed 650\n", "Completed 700\n", "Completed 750\n", "Completed 800\n", "Completed 850\n", "\n", "Queries without join results:\n", "Percent valid: 0.7916181606519208\n", "Percent SQLite matched: 0.17462165308498254\n", "Percent result matched: 0.42374854481955765\n", "Dataset length: 859\n" ] } ], "source": [ "no_join_queries = pd.read_csv(\"./train-data/without_join.tsv\", sep='\\t')\n", "run_evaluation(no_join_queries, \"Queries without join\")\n", "print(\"Dataset length: \" + str(len(no_join_queries)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Evaluate on full training dataset" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Completed 50\n", "Completed 100\n", "Completed 150\n", "Completed 200\n", "Completed 250\n", "Completed 300\n", "Completed 350\n", "Completed 400\n", "Completed 450\n", "Completed 500\n", "Completed 550\n", "Completed 600\n", "Completed 650\n", "Completed 700\n", "Completed 750\n", "Completed 800\n", "Completed 850\n", "Completed 900\n", "Completed 950\n", "Completed 1000\n", "\n", "All training data results:\n", "Percent valid: 0.685823754789272\n", "Percent SQLite matched: 0.14367816091954022\n", "Percent result matched: 0.35823754789272033\n", "Dataset length: 1044\n" ] } ], "source": [ "# Run evaluation on all training data\n", "run_evaluation(df, \"All training data\")\n", "print(\"Dataset length: \" + str(len(df)))" ] } ], "metadata": { "kernelspec": { "display_name": "CSCI544", "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.11.11" } }, "nbformat": 4, "nbformat_minor": 2 }