--- 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" --- # Update: 14-03-2024 - The model card is still updating. 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 [optional]:** [microsoft/phi-2](https://huggingface.co/microsoft/phi-2) ### Model Sources [optional] - **Repository:** [pavankumarbalijepalli/pr-phi2-vs-defog](https://github.com/pavankumarbalijepalli/pr-phi2-vs-defog/) - **Paper [optional]:** [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 import torch from transformers import AutoModelForCausalLM, AutoTokenizer from peft import PeftModel, PeftConfig model_name = "microsoft/phi-2" 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(new_prompt, return_tensors="pt", padding=True, truncation=True) inputs.to('cuda') model_id = "pavankumarbalijepalli/phi2-sqlcoder" trained_model = PeftModel.from_pretrained(model, model_id) outputs = trained_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 [More Information Needed] ``` @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 [More Information Needed] #### Factors [More Information Needed] #### Metrics [More Information Needed] ### Results [More Information Needed] #### Summary ## 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:** [More Information Needed] - **Hours used:** [More Information Needed] - **Cloud Provider:** [More Information Needed] - **Compute Region:** [More Information Needed] - **Carbon Emitted:** [More Information Needed] ## Citation [optional] **BibTeX:** ``` @misc {pavan_kumar_balijepalli_2024, author = { {Pavan Kumar Balijepalli} }, title = { phi2-sqlcoder (Revision 2391b6b) }, year = 2024, url = { https://huggingface.co/pavankumarbalijepalli/phi2-sqlcoder }, doi = { 10.57967/hf/1884 }, publisher = { Hugging Face } } ```