--- license: mit datasets: - b-mc2/sql-create-context language: - en metrics: - accuracy - code_eval library_name: transformers pipeline_tag: text-generation tags: - peft - nl2sql widget: - text: "### Task\nGenerate a SQL query to answer the following question:\n`How many heads of the departments are older than 56?`\n\n### Database Schema\nThe query will run on a database with the following schema:\nCREATE TABLE head (age INTEGER)\n\n### Answer\nGiven the database schema, here is the SQL query that answers `How many heads of the departments are older than 56?`:\n```sql" example_title: "One Table" - text: "### Task\nGenerate a SQL query to answer the following question:\n`How many departments are led by heads who are not mentioned?`\n\n### Database Schema\nThe query will run on a database with the following schema:\nCREATE TABLE management (department_id VARCHAR);\nCREATE TABLE department (department_id VARCHAR)\n\n### Answer\nGiven the database schema, here is the SQL query that answers `How many departments are led by heads who are not mentioned?`:\n```sql" example_title: "Two Tables" --- # Thanks for being patient! 💜💜 # Model Card for Model ID A fine-tuned version of Phi-2 for the NL2SQL usecase on `b-mc2/sql-create-context` dataset. ## Model Details ### Model Description This model has been finetuned with `b-mc2/sql-create-context` on `microsoft/phi-2`. This performed better than `defog/sqlcoder-7b-2` in terms of inference time and accuracy on the holdback dataset. The evaluation is done on `.gguf` models on CPU machine with limited RAM. The average inference times of the Phi-2, and SQLCoder are 24 secs, and 41 secs respectively. That is 41% faster on average. This is due to its smaller size. The Finetuned Phi-2 is 29% better than the SQLCoder based on execution success. The major drawback is its context window of 2048 tokens which requires additional input engineering to get results. - **Developed by:** pavankumarbalijepalli - **Model type:** CASUAL_LM - **Language(s) (NLP):** English, SQL - **License:** MIT - **Finetuned from model:** [microsoft/phi-2](https://huggingface.co/microsoft/phi-2) ### Model Sources - **Repository:** [pavankumarbalijepalli/pr-phi2-vs-defog](https://github.com/pavankumarbalijepalli/pr-phi2-vs-defog/) - **Paper :** [BITS Project Paper](https://github.com/pavankumarbalijepalli/pr-phi2-vs-defog/blob/main/2021SC04115%20-%20Final.pdf) ## Uses Model is supposed to be used for the cases where you have a natural language question, database schema which is relevant the question to retrieve a SQL query which answers the question. The context should be below 2048 tokens. The output will be generated in postgresql. ### Direct Use ```python # SAME TEMPLATE AS DEFOG MODEL prompt = f"""### Task Generate a SQL query to answer the following question: `{data_point['question']}` ### Database Schema The query will run on a database with the following schema: {data_point['context']} ### Answer Given the database schema, here is the SQL query that answers `{data_point['question']}`: ```sql""" ``` ```python # USING ON CPU MACHINE from llama_cpp import Llama phi2 = Llama(model_path=f"{path_to_model}/phi2_sqlcoder_f16.gguf") response = phi2(prompt=prompt, max_tokens = 200, temperature = 0.2, stop = ['```']) print(response['choices'][0]['text'].strip()) ``` ### Downstream Use ```python # USING ON GPU MACHINE import torch from transformers import AutoModelForCausalLM, AutoTokenizer from peft import PeftModel, PeftConfig model_name = "pavankumarbalijepalli/phi2-sqlcoder" model = AutoModelForCausalLM.from_pretrained( model_name, trust_remote_code=True, device_map="auto" ) tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True) inputs = tokenizer(prompt, return_tensors="pt", padding=True, truncation=True) inputs.to('cuda') outputs = model.generate(**inputs, max_length=1000) text = tokenizer.batch_decode(outputs,skip_special_tokens=True)[0] print(text) ``` ### Out-of-Scope Use __Generating Unintended Code:__ While the model can translate natural language into SQL queries, it may not be robust enough to handle complex logic or edge cases. Using it to generate critical production code could lead to errors or unexpected behavior in databases. __Security Risks:__ NL2SQL models can be susceptible to adversarial attacks where malicious users input natural language designed to trick the model into generating SQL code with security vulnerabilities, like SQL injection attacks. __Beyond its Training Scope:__ The model is trained on a specific SQL Language (e.g., PostgreSQL). Using it for a different SQL Syntax (e.g., MS SQL Server) could lead to inaccurate or nonsensical SQL queries. ## Bias, Risks, and Limitations __Bias and Fairness:__ The model's training data may contain biases that are reflected in the generated SQL queries. This could lead to unfair or discriminatory outcomes, especially if the data is not carefully curated. __Interpretability and Explainability:__ NL2SQL models are often "black boxes" where it's difficult to understand how they translate natural language to SQL. This lack of interpretability makes it challenging to debug errors or ensure the generated queries are safe and efficient. __Replacing Human Expertise:__ While the model can automate some SQL query generation tasks, it shouldn't be a complete replacement for human database administrators or analysts. Understanding the data schema and database design is crucial for writing efficient and secure SQL queries. ### Recommendations Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. ## Training Details ### Training Data ``` @misc{b-mc2_2023_sql-create-context, title = {sql-create-context Dataset}, author = {b-mc2}, year = {2023}, url = {https://huggingface.co/datasets/b-mc2/sql-create-context}, note = {This dataset was created by modifying data from the following sources: \cite{zhongSeq2SQL2017, yu2018spider}.}, } ``` ## Evaluation ### Testing Data, Factors & Metrics #### Testing Data Used b-mc2/sql-create-context and split the data into training and testing datasets. The holdout dataset is used for testing the model. #### Factors The complexity of the questions are calculated using the number of tables per question, number of joins, group by, and sub queries per answer. This complexity is used to prepare the test data by stratifying the split around the complexity. #### Metrics * __Execution Success:__ This metric is used to find out if the generated query is executable without arising any errors. For this, a sqllite3 connection is made to the memory, and using context the dummy tables are created. Then the predicted SQL is executed. This checks out if the generated query is in proper syntax, and if the model is hallucinating any new columns. * __Inference Time:__ This metric is used to find out which model is providing results in less amount of time. This combined with the execution success, gives the efficiency of the model. - ### Results * __Execution Success:__ Finetuned Phi-2 has 29% more success rate than the SQLCoder-7b-2 * __Inference Time:__ Finetuned Phi-2 has 41% increased inference speed than SQLCoder-7b-2 #### Summary * __Reduced Inference Time and Memory Footprint:__ The fine-tuned Phi-2 model demonstrated a reduction in inference time and memory usage compared to the DeFog SQLCoder. This is attributed to Phi-2's smaller size and the efficiency of quantization techniques employed during fine-tuning. This finding implies that NL2SQL models can be deployed on lower-powered devices like laptops or even mobile phones, potentially democratizing access to this technology for a wider range of users. * __Competitive Performance on Easy and Medium Queries:__ The fine-tuned Phi-2 achieved comparable performance to the DeFog SQLCoder in terms of accuracy on easy, medium, and hard difficulty queries. This indicates that Phi-2, despite its smaller size, can effectively handle a significant portion of real-world NL2SQL tasks, especially for simpler queries. * __Challenges with Complex Queries:__ While Phi-2 performed well on easier queries, it encountered challenges with complex queries, exhibiting a drop in execution success compared to the DeFog SQLCoder. This highlights the trade-off between model size and complexity, suggesting that larger models might still be necessary for tackling highly intricate tasks. * __Potential for Further Improvement:__ The fine-tuning process employed in this study can be further optimized by exploring different hyperparameter configurations and potentially investigating alternative fine-tuning techniques like adapter-based methods. This optimization has the potential to improve the model's performance on complex queries while maintaining its efficiency. ## Environmental Impact Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700). - **Hardware Type:** A100 PCIE 40GB X1 - **Hours used:** 18 Hours - **Cloud Provider:** Google Cloud - **Compute Region:** Asia-East-1 - **Carbon Emitted:** 2.52 kg eq. CO2 ## Citation **BibTeX:** ``` @misc {pavan_kumar_balijepalli_2024, author = { {Pavan Kumar Balijepalli} }, title = { phi2-sqlcoder (Revision 7a5dc3a) }, year = 2024, url = { https://huggingface.co/pavankumarbalijepalli/phi2-sqlcoder }, doi = { 10.57967/hf/1886 }, publisher = { Hugging Face } } ```