File size: 11,379 Bytes
cd207c5
2391b6b
 
 
 
 
 
 
 
 
 
 
 
 
0b236c2
 
0465503
049b12f
369dc3b
cd207c5
 
369dc3b
cd207c5
2391b6b
26ebc5f
cd207c5
 
2391b6b
cd207c5
 
 
 
 
 
2391b6b
cd207c5
2391b6b
 
 
 
7a5dc3a
cd207c5
7a5dc3a
cd207c5
 
 
2391b6b
7a5dc3a
cd207c5
 
 
 
 
2391b6b
 
cd207c5
 
 
 
2391b6b
 
 
 
 
 
 
 
 
 
 
 
 
 
cd207c5
2391b6b
 
 
 
 
 
 
 
 
 
 
 
cd207c5
 
 
2391b6b
41f9f32
2391b6b
 
75cb7bd
2391b6b
41f9f32
2391b6b
 
 
 
 
 
 
75cb7bd
 
2391b6b
75cb7bd
41f9f32
2391b6b
 
41f9f32
2391b6b
 
 
cd207c5
 
 
 
 
2391b6b
 
 
 
 
 
 
 
 
 
 
cd207c5
 
 
 
 
2391b6b
 
 
 
 
 
 
 
 
 
 
 
cd207c5
 
 
 
 
9153c89
cd207c5
 
 
 
 
 
 
2391b6b
 
 
 
 
 
 
 
 
cd207c5
 
 
 
 
 
 
 
 
 
 
369dc3b
cd207c5
 
 
 
369dc3b
cd207c5
 
 
 
 
369dc3b
 
 
cd207c5
 
369dc3b
 
cd207c5
 
369dc3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd207c5
 
 
 
 
 
 
369dc3b
 
 
 
 
cd207c5
 
7a5dc3a
cd207c5
 
 
 
9153c89
 
 
01228be
9153c89
 
01228be
9153c89
 
 
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
---
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

<!-- Provide a quick summary of what the model is/does. -->

A fine-tuned version of Phi-2 for the NL2SQL usecase on `b-mc2/sql-create-context` dataset. 

## Model Details

### Model Description

<!-- Provide a longer summary of what this model is. -->
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

<!-- Provide the basic links for the model. -->

- **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

<!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->

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

<!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->

```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

<!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->

```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"
)

prompt = ""

tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
tokenizer.pad_token = tokenizer.eos_token
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

<!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->

__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

<!-- This section is meant to convey both technical and sociotechnical 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

<!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->

Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model.

## Training Details

### Training Data

<!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->

```
@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

<!-- This section describes the evaluation protocols and provides the results. -->

### Testing Data, Factors & Metrics

#### Testing Data

<!-- This should link to a Dataset Card if possible. -->

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

<!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
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

<!-- These are the evaluation metrics being used, ideally with a description of why. -->
* __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

<!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->

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

<!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->

**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 }
}
```