abharadwaj123 commited on
Commit
3f02af0
·
verified ·
1 Parent(s): 920b77e

Create README.md

Browse files
Files changed (1) hide show
  1. README.md +220 -0
README.md ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ base_model:
4
+ - meta-llama/Llama-3.2-3B
5
+ library_name: peft
6
+ ---
7
+ # Model Card for llama3-sql2plan
8
+
9
+ This model is a fine-tuned version of [meta-llama/Llama-3.2-3B](https://huggingface.co/meta-llama/Llama-3.2-3B) using LoRA (Low-Rank Adaptation) for the task of generating PostgreSQL execution plans from SQL queries. The model takes SQL queries as input and outputs the corresponding PostgreSQL execution plan in JSON format.
10
+
11
+ ## Model Details
12
+
13
+ ### Model Description
14
+
15
+ This model is specifically designed to convert SQL queries into PostgreSQL execution plans. It was fine-tuned using Parameter-Efficient Fine-Tuning (PEFT) with LoRA adapters, allowing efficient training while maintaining the base model's capabilities.
16
+
17
+ - **Developed by:** Anirudh Bharadwaj
18
+ - **Model type:** Causal Language Model (Decoder-only)
19
+ - **Language(s) (NLP):** English (SQL and JSON)
20
+ - **License:** Apache 2.0
21
+ - **Finetuned from model:** [meta-llama/Llama-3.2-3B](https://huggingface.co/meta-llama/Llama-3.2-3B)
22
+
23
+ ### Model Sources
24
+
25
+ - **Repository:** [abharadwaj123/llama3-sql2plan](https://huggingface.co/abharadwaj123/llama3-sql2plan)
26
+ - **Base Model:** [meta-llama/Llama-3.2-3B](https://huggingface.co/meta-llama/Llama-3.2-3B)
27
+
28
+ ## Uses
29
+
30
+ ### Direct Use
31
+
32
+ This model can be used directly to generate PostgreSQL execution plans from SQL queries. It is intended for:
33
+
34
+ - Database query optimization analysis
35
+ - Understanding query execution strategies
36
+ - Educational purposes for learning PostgreSQL query planning
37
+ - Database performance analysis tools
38
+
39
+ ### Example Usage
40
+
41
+ ```python
42
+ from transformers import AutoTokenizer, AutoModelForCausalLM
43
+ import torch
44
+
45
+ model_name = "abharadwaj123/llama3-sql2plan"
46
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
47
+ model = AutoModelForCausalLM.from_pretrained(
48
+ model_name,
49
+ torch_dtype=torch.bfloat16,
50
+ device_map="auto",
51
+ )
52
+
53
+ sql_query = "SELECT * FROM users WHERE age > 25;"
54
+ prompt = (
55
+ "Generate the PostgreSQL execution plan in JSON format for the SQL query.\n\n"
56
+ "[QUERY]\n" + sql_query + "\n\n[PLAN]\n"
57
+ )
58
+
59
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
60
+ with torch.no_grad():
61
+ outputs = model.generate(
62
+ **inputs,
63
+ max_new_tokens=256,
64
+ temperature=0.7,
65
+ do_sample=True,
66
+ )
67
+
68
+ generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
69
+ plan = generated_text.split("[PLAN]\n")[-1].strip()
70
+ print(plan)
71
+ ```
72
+
73
+ ### Out-of-Scope Use
74
+
75
+ This model should not be used for:
76
+ - Generating actual executable SQL queries (it generates execution plans, not queries)
77
+ - Real-time database query execution
78
+ - Production database systems without proper validation
79
+ - Any use case requiring guaranteed accuracy of execution plans
80
+
81
+ ## Bias, Risks, and Limitations
82
+
83
+ ### Limitations
84
+
85
+ - **Accuracy**: The model generates execution plans based on training data patterns and may not always produce accurate or optimal plans for all SQL queries.
86
+ - **PostgreSQL-specific**: The model is trained specifically for PostgreSQL execution plans and may not be suitable for other database systems.
87
+ - **Training Data Scope**: The model was trained on a subset of Stack Overflow data (10,000 samples from ~16,332 available), which may not cover all SQL query patterns.
88
+ - **No Database Context**: The model does not have access to actual database schema, indexes, or statistics, which are crucial for accurate execution plan generation.
89
+
90
+ ### Recommendations
91
+
92
+ Users should:
93
+ - Validate generated execution plans against actual PostgreSQL EXPLAIN output
94
+ - Not rely solely on this model for critical database optimization decisions
95
+ - Use this model as a tool for understanding and learning, not as a replacement for actual database query planning
96
+ - Be aware that execution plans may vary based on database configuration, schema, and data distribution
97
+
98
+ ## How to Get Started with the Model
99
+
100
+ ```python
101
+ from transformers import AutoTokenizer, AutoModelForCausalLM
102
+ import torch
103
+
104
+ # Load model and tokenizer
105
+ model_name = "abharadwaj123/llama3-sql2plan"
106
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
107
+ model = AutoModelForCausalLM.from_pretrained(
108
+ model_name,
109
+ torch_dtype=torch.bfloat16,
110
+ device_map="auto",
111
+ )
112
+
113
+ # Prepare input
114
+ sql_query = "SELECT * FROM users WHERE age > 25;"
115
+ prompt = (
116
+ "Generate the PostgreSQL execution plan in JSON format for the SQL query.\n\n"
117
+ "[QUERY]\n" + sql_query + "\n\n[PLAN]\n"
118
+ )
119
+
120
+ # Generate plan
121
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
122
+ outputs = model.generate(
123
+ **inputs,
124
+ max_new_tokens=256,
125
+ temperature=0.7,
126
+ do_sample=True,
127
+ )
128
+
129
+ # Extract plan
130
+ generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
131
+ plan = generated_text.split("[PLAN]\n")[-1].strip()
132
+ ```
133
+
134
+ ## Training Details
135
+
136
+ ### Training Data
137
+
138
+ The model was trained on a dataset derived from Stack Overflow data (`stackoverflow_n18147.csv`), containing SQL queries and their corresponding PostgreSQL execution plans in JSON format.
139
+
140
+ - **Total samples in dataset:** 18,147
141
+ - **Training samples used:** 10,000 (sampled from first 90% of dataset, ~16,332 samples)
142
+ - **Sampling method:** Random sampling with random_state=42
143
+ - **Data format:** SQL query text paired with PostgreSQL execution plan JSON
144
+
145
+ The training data was filtered to remove rows with missing `sql_text` or `plan_json` values.
146
+
147
+ ### Training Procedure
148
+
149
+ #### Preprocessing
150
+
151
+ 1. **Data Loading**: Loaded CSV file and filtered out rows with missing SQL text or plan JSON
152
+ 2. **Data Splitting**: Used first 90% of dataset as training pool, then randomly sampled 10,000 examples
153
+ 3. **Formatting**: Each example was formatted with a prompt template:
154
+ ```
155
+ Generate the PostgreSQL execution plan in JSON format for the SQL query.
156
+
157
+ [QUERY]
158
+ {sql_text}
159
+
160
+ [PLAN]
161
+ {plan_json}
162
+ ```
163
+ 4. **Tokenization**:
164
+ - Maximum sequence length: 2048 tokens
165
+ - Input prompt tokens were masked in labels (set to -100) to only train on plan generation
166
+ - Padding to max_length
167
+
168
+ #### Training Hyperparameters
169
+
170
+ - **Training regime:** FP16 mixed precision training
171
+ - **LoRA Configuration:**
172
+ - `r`: 64
173
+ - `lora_alpha`: 32
174
+ - `lora_dropout`: 0.05
175
+ - `target_modules`: ["q_proj", "k_proj", "v_proj", "o_proj"]
176
+ - **Training Arguments:**
177
+ - `per_device_train_batch_size`: 2
178
+ - `gradient_accumulation_steps`: 8
179
+ - `effective_batch_size`: 16
180
+ - `learning_rate`: 1e-5
181
+ - `warmup_ratio`: 0.03
182
+ - `num_train_epochs`: 2
183
+ - `gradient_checkpointing`: True
184
+ - `logging_steps`: 20
185
+ - `save_strategy`: "epoch"
186
+
187
+
188
+ #### Testing Data
189
+
190
+ The remaining 10% of the original dataset (~1,815 samples) was held out and could be used for evaluation.
191
+
192
+ ## Model Examination
193
+
194
+ The model uses LoRA (Low-Rank Adaptation) fine-tuning, which allows efficient training by only updating a small number of parameters (low-rank matrices) while keeping the base model weights frozen. This approach:
195
+
196
+ - Reduces memory requirements during training
197
+ - Enables faster training compared to full fine-tuning
198
+ - Maintains the base model's general capabilities
199
+ - Allows easy merging of adapters with the base model
200
+
201
+
202
+ ## Technical Specifications
203
+
204
+ ### Model Architecture and Objective
205
+
206
+ - **Architecture:** Transformer-based decoder-only language model (Llama-3.2-3B)
207
+ - **Objective:** Causal language modeling with masked input tokens
208
+ - **Fine-tuning Method:** LoRA (Low-Rank Adaptation) via PEFT
209
+ - **Base Model Parameters:** ~3 billion
210
+ - **Trainable Parameters:** Significantly reduced via LoRA (exact count depends on LoRA rank and target modules)
211
+
212
+
213
+ ## Model Card Authors
214
+
215
+ Anirudh Bharadwaj
216
+
217
+ ## Model Card Contact
218
+
219
+ For questions or issues, please contact through the Hugging Face model repository: [abharadwaj123/llama3-sql2plan](https://huggingface.co/abharadwaj123/llama3-sql2plan)
220
+