suan-chang commited on
Commit
84c630e
·
1 Parent(s): 268ed01

update README.md

Browse files
.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ test.py
2
+ test_eval.py
3
+ *.pyc
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README-zh.md ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 引言
2
+ [Rain's SQLCoder](https://huggingface.co/SuanChang/rain-SQLCoder) 是自然语言生成 SparkSQL 的 SOTA 大型语言模型(LLM),拥有 32B 参数,基于 [Qwen2.5-Coder-32B-Instruct](https://huggingface.co/Qwen/Qwen2.5-Coder-32B-Instruct) 微调。 Rain's SQLCoder 针对自然语言到 SparkSQL 转换任务进行了优化,能够有效处理最长达 32k 个 token 的上下文,尤其适用于复杂且大规模的 SQL 查询生成任务。
3
+
4
+ <p align="center">
5
+ 🤗 <a href="https://huggingface.co/SuanChang/rain-SQLCoder">Hugging Face</a> | 🖥️ <a href="https://www.suan-chang.com/">演示</a> | 💬 <a href="./figures/wechat.png">微信</a> | <a href="https://github.com/suan-chang/rain-SQLCoder">GitHub</a>
6
+ </p>
7
+
8
+ [English](./README.md) | [中文](./README-zh.md)
9
+
10
+ # 提示词
11
+ Rain's SQLCoder 采用了 [Alpaca](https://github.com/tatsu-lab/stanford_alpaca) 模板,使用的提示词如下。
12
+ ````
13
+ Below is an instruction that describes a task.
14
+ Write a response that appropriately completes the request.
15
+
16
+ ### Instruction:
17
+ [BEGIN OF TASK INSTRUCTION]
18
+ You are an expert in composing Spark SQL queries. You are given a user query and a set of table schemas.
19
+ Based on the user query, you need to generate one Spark SQL query to achieve the purpose.
20
+ {task description for date hint and related question and sqls}
21
+ [END OF TASK INSTRUCTION]
22
+
23
+ [BEGIN OF TABLE SCHEMAS]
24
+ {schemas}
25
+ [END OF TABLE SCHEMAS]
26
+
27
+ [BEGIN OF GENERATION HINT]
28
+ {date hint}
29
+ [END OF GENERATION HINT]
30
+
31
+ [BEGIN OF RELATED QUERIES]
32
+ {related question and sqls}
33
+ [END OF RELATED QUERIES]
34
+
35
+ [BEGIN OF FORMAT INSTRUCTION]
36
+ The output MUST strictly adhere to the following format, and NO other text MUST be included.
37
+ ```sql
38
+ your output Spark SQL query
39
+ ```
40
+ [END OF FORMAT INSTRUCTION]
41
+
42
+ [BEGIN OF QUERY]
43
+ User Query: {user question}
44
+ [END OF QUERY]
45
+
46
+ ### Response:
47
+ ````
48
+
49
+ # 评估
50
+ 我们沿用了 [SQL-Eval](https://github.com/defog-ai/sql-eval) 中评估预测结果与标准结果的逻辑:
51
+ 1. 如果预测的数据块和标准数据块完全一致,则预测结果正确;
52
+ 2. 标准SQL中不包含排序逻辑,且预测数据块和标准数据块在排序之后完全一致,则预测结果正确;
53
+ 3. 如果标准数据块的列是预测数据块的子集,则预测结果正确;
54
+ 4. 其余情况均认为预测结果错误。
55
+
56
+ # 实验结果
57
+ 我们在两个测试集上对比了Rain's SQLCoder与国内外先进自然语言大模型的生成准确率。其中,基准测试集(Benchmark Dataset)包含基础样本,而增强测试集(Enhanced Dataset)则是在基准测试集的基础上,通过分层抽样方法选取20%的样本,并补充了相关的用户查询及对应的SparkSQL语句,以评估模型在增强上下文信息下的性能表现。实验结果表明,Rain's SQLCoder在查询意图理解、SQL语法准确性和复杂查询处理等方面均展现出显著优势。
58
+
59
+ ## 基准测试集
60
+ <img src="./figures/benchmark_dataset_result.png" alt="benchmark" width=800>
61
+
62
+ ## 增强测试集
63
+ <img src="./figures/enhanced_dataset_result.png" alt="enhanced" width=800>
64
+
65
+ # 快速开始
66
+ 我们在此处提供示例,帮助您快速掌握如何加载并使用我们的模型。
67
+ >注意: Rain's SQLCoder 只被训练用于生成 `SELECT` 语句,当表结构无法支持回答用户问题时,模型会拒绝回答。
68
+
69
+ ````python
70
+ import torch
71
+ from transformers import AutoModelForCausalLM, AutoTokenizer
72
+ from utils.prompt import SQLGeneratePrompt
73
+
74
+ model_name = "SuanChang/rain-SQLCoder"
75
+
76
+ model = AutoModelForCausalLM.from_pretrained(
77
+ model_name,
78
+ torch_dtype=torch.bfloat16,
79
+ device_map="auto",
80
+ )
81
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
82
+
83
+ question = "What is the name of the department that offers a course that has a description including the word 'Statistics'?"
84
+ schemas = [
85
+ '''CREATE TABLE `course` (
86
+ `crs_code` STRING,
87
+ `dept_code` STRING,
88
+ `crs_description` STRING,
89
+ `crs_credit` DOUBLE
90
+ );''',
91
+ '''CREATE TABLE `department` (
92
+ `dept_code` STRING,
93
+ `dept_name` STRING,
94
+ `school_code` STRING,
95
+ `emp_num` INT,
96
+ `dept_address` STRING,
97
+ `dept_extension` INT
98
+ );''',
99
+ '''CREATE TABLE `student` (
100
+ `stu_num` INT,
101
+ `stu_lname` STRING,
102
+ `stu_fname` STRING,
103
+ `stu_init` STRING,
104
+ `stu_dob` STRING,
105
+ `stu_hrs` INT,
106
+ `stu_class` STRING,
107
+ `stu_gpa` DOUBLE,
108
+ `stu_transfer` INT,
109
+ `dept_code` STRING,
110
+ `stu_phone` INT,
111
+ `prof_num` INT
112
+ );'''
113
+ ]
114
+ hint = "- Today is 2025-02-01."
115
+ data = dict(
116
+ question=question,
117
+ schema="\n\n".join(schemas),
118
+ hint=hint,
119
+ related_question_sqls=None,
120
+ )
121
+ text, _, _ = SQLGeneratePrompt.prompt(data)
122
+
123
+ model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
124
+
125
+ generated_ids = model.generate(
126
+ **model_inputs,
127
+ max_new_tokens=32768
128
+ )
129
+ generated_ids = [
130
+ output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
131
+ ]
132
+ response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
133
+
134
+ print(response)
135
+
136
+ '''
137
+ ```sql
138
+ SELECT d.dept_name FROM department d JOIN course c ON d.dept_code = c.dept_code WHERE c.crs_description LIKE '%Statistics%';
139
+ ```
140
+ '''
141
+ ````
README.md CHANGED
@@ -1,3 +1,141 @@
1
- ---
2
- license: apache-2.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Introduction
2
+ [Rain's SQLCoder](https://huggingface.co/SuanChang/rain-SQLCoder) is a state-of-the-art large language model (LLM) designed for natural language-to-SparkSQL generation. Rain's SQLCoder, with 32B parameters, is fine-tuned from the [Qwen2.5-Coder-32B-Instruct](https://huggingface.co/Qwen/Qwen2.5-Coder-32B-Instruct). Optimized for natural language-to-SparkSQL conversion tasks, Rain's SQLCoder effectively handles contexts of up to 32k tokens, making it particularly suitable for generating complex and large-scale SQL queries.
3
+
4
+ <p align="center">
5
+ 🤗 <a href="https://huggingface.co/SuanChang/rain-SQLCoder">Hugging Face</a> | 🖥️ <a href="https://www.suan-chang.com/">Demo</a> | 💬 <a href="./figures/wechat.png">WeChat</a> | <a href="https://github.com/suan-chang/rain-SQLCoder">GitHub</a>
6
+ </p>
7
+
8
+ [English](./README.md) | [中文](./README-zh.md)
9
+
10
+ # Prompt
11
+ Rain's SQLCoder adopted the [Alpaca](https://github.com/tatsu-lab/stanford_alpaca) template, with the following prompt format.
12
+ ````
13
+ Below is an instruction that describes a task.
14
+ Write a response that appropriately completes the request.
15
+
16
+ ### Instruction:
17
+ [BEGIN OF TASK INSTRUCTION]
18
+ You are an expert in composing Spark SQL queries. You are given a user query and a set of table schemas.
19
+ Based on the user query, you need to generate one Spark SQL query to achieve the purpose.
20
+ {task description for date hint and related question and sqls}
21
+ [END OF TASK INSTRUCTION]
22
+
23
+ [BEGIN OF TABLE SCHEMAS]
24
+ {schemas}
25
+ [END OF TABLE SCHEMAS]
26
+
27
+ [BEGIN OF GENERATION HINT]
28
+ {date hint}
29
+ [END OF GENERATION HINT]
30
+
31
+ [BEGIN OF RELATED QUERIES]
32
+ {related question and sqls}
33
+ [END OF RELATED QUERIES]
34
+
35
+ [BEGIN OF FORMAT INSTRUCTION]
36
+ The output MUST strictly adhere to the following format, and NO other text MUST be included.
37
+ ```sql
38
+ your output Spark SQL query
39
+ ```
40
+ [END OF FORMAT INSTRUCTION]
41
+
42
+ [BEGIN OF QUERY]
43
+ User Query: {user question}
44
+ [END OF QUERY]
45
+
46
+ ### Response:
47
+ ````
48
+
49
+ # Evaluation
50
+ We followed the evaluation logic from [SQL-Eval](https://github.com/defog-ai/sql-eval) to compare predicted results with ground truth:
51
+ 1. If the predicted data frame exactly matches the ground truth data frame, the prediction is considered correct.
52
+ 2. If the ground truth SQL does not contain sorting logic, and the predicted data frame matches the ground truth data frame after sorting, the prediction is considered correct.
53
+ 3. If the columns in the ground truth data frame are a subset of the predicted data frame, the prediction is considered correct.
54
+ 4. In all other cases, the prediction is considered incorrect.
55
+
56
+ # Experimental Results
57
+ We compared the generation accuracy of Rain's SQLCoder with state-of-the-art natural language large models, both domestic and international, on two test datasets. The Benchmark Dataset contains baseline samples, while the Enhanced Dataset is constructed by applying stratified sampling to 20% of the Benchmark Dataset and supplementing it with relevant user questions and corresponding SparkSQL statements to evaluate the model's performance under enhanced contextual information. The experimental results demonstrate that Rain's SQLCoder exhibits significant advantages in query intent understanding, SQL syntax accuracy, and complex query processing.
58
+
59
+ ## Benchmark Dataset
60
+ <img src="./figures/benchmark_dataset_result.png" alt="benchmark" width=800>
61
+
62
+ ## Enhanced Dataset
63
+ <img src="./figures/enhanced_dataset_result.png" alt="enhanced" width=800>
64
+
65
+ # Quick Start
66
+ We provide examples here to help you quickly learn how to load and use our model.
67
+ >Tips: Rain's SQLCoder is trained solely for generating `SELECT` statements, and when the table schemas cannot support answering the user's question, the model will refuse to respond.
68
+
69
+ ````python
70
+ import torch
71
+ from transformers import AutoModelForCausalLM, AutoTokenizer
72
+ from utils.prompt import SQLGeneratePrompt
73
+
74
+ model_name = "SuanChang/rain-SQLCoder"
75
+
76
+ model = AutoModelForCausalLM.from_pretrained(
77
+ model_name,
78
+ torch_dtype=torch.bfloat16,
79
+ device_map="auto",
80
+ )
81
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
82
+
83
+ question = "What is the name of the department that offers a course that has a description including the word 'Statistics'?"
84
+ schemas = [
85
+ '''CREATE TABLE `course` (
86
+ `crs_code` STRING,
87
+ `dept_code` STRING,
88
+ `crs_description` STRING,
89
+ `crs_credit` DOUBLE
90
+ );''',
91
+ '''CREATE TABLE `department` (
92
+ `dept_code` STRING,
93
+ `dept_name` STRING,
94
+ `school_code` STRING,
95
+ `emp_num` INT,
96
+ `dept_address` STRING,
97
+ `dept_extension` INT
98
+ );''',
99
+ '''CREATE TABLE `student` (
100
+ `stu_num` INT,
101
+ `stu_lname` STRING,
102
+ `stu_fname` STRING,
103
+ `stu_init` STRING,
104
+ `stu_dob` STRING,
105
+ `stu_hrs` INT,
106
+ `stu_class` STRING,
107
+ `stu_gpa` DOUBLE,
108
+ `stu_transfer` INT,
109
+ `dept_code` STRING,
110
+ `stu_phone` INT,
111
+ `prof_num` INT
112
+ );'''
113
+ ]
114
+ hint = "- Today is 2025-02-01."
115
+ data = dict(
116
+ question=question,
117
+ schema="\n\n".join(schemas),
118
+ hint=hint,
119
+ related_question_sqls=None,
120
+ )
121
+ text, _, _ = SQLGeneratePrompt.prompt(data)
122
+
123
+ model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
124
+
125
+ generated_ids = model.generate(
126
+ **model_inputs,
127
+ max_new_tokens=32768
128
+ )
129
+ generated_ids = [
130
+ output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
131
+ ]
132
+ response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
133
+
134
+ print(response)
135
+
136
+ '''
137
+ ```sql
138
+ SELECT d.dept_name FROM department d JOIN course c ON d.dept_code = c.dept_code WHERE c.crs_description LIKE '%Statistics%';
139
+ ```
140
+ '''
141
+ ````
figures/benchmark_dataset_result.png ADDED
figures/enhanced_dataset_result.png ADDED
figures/wechat.png ADDED
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ func_timeout==4.3.5
2
+ pandas==2.2.3
3
+ torch==2.3.1
4
+ transformers==4.43.4
utils/eval.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import pandas as pd
3
+ from func_timeout import func_timeout, FunctionTimedOut
4
+ import pandas as pd
5
+ from pandas.testing import assert_frame_equal, assert_series_equal
6
+ import collections
7
+
8
+
9
+ LIKE_PATTERN = r"LIKE[\s\S]*'"
10
+
11
+
12
+ def deduplicate_columns(df: pd.DataFrame) -> pd.DataFrame:
13
+ cols = df.columns.tolist()
14
+ if len(cols) != len(set(cols)):
15
+ duplicates = [
16
+ item for item, count in collections.Counter(cols).items() if count > 1
17
+ ]
18
+ for dup in duplicates:
19
+ indices = [i for i, x in enumerate(cols) if x == dup]
20
+ for i in indices:
21
+ cols[i] = f"{dup}_{i}"
22
+ df.columns = cols
23
+ return df
24
+
25
+
26
+ def serializate_columns(df: pd.DataFrame):
27
+ for col in df.columns:
28
+ if df[col].apply(lambda x: isinstance(x, (list, pd.Series))).any():
29
+ df[col] = df[col].apply(
30
+ lambda x: str(sorted(x)) if isinstance(x, (list, pd.Series)) else x
31
+ )
32
+ return df
33
+
34
+
35
+ def normalize_table(
36
+ df: pd.DataFrame, query_category: str, if_order: bool, sql: str = None
37
+ ) -> pd.DataFrame:
38
+ """
39
+ Normalizes a dataframe by:
40
+ 1. removing all duplicate rows
41
+ 2. sorting columns in alphabetical order
42
+ 3. sorting rows using values from first column to last (if query_category is not 'order_by' and question does not ask for ordering)
43
+ 4. resetting index
44
+ """
45
+ df = serializate_columns(df)
46
+
47
+ # remove duplicate rows, if any
48
+ df = df.drop_duplicates()
49
+
50
+ # sort columns in alphabetical order of column names
51
+ df = deduplicate_columns(df)
52
+ sorted_df = df.reindex(sorted(df.columns), axis=1)
53
+
54
+ # check if query_category is 'order_by' and if question asks for ordering
55
+ has_order_by = False
56
+
57
+ if query_category == "order_by" or if_order:
58
+ has_order_by = True
59
+
60
+ if sql:
61
+ # determine which columns are in the ORDER BY clause of the sql generated, using regex
62
+ pattern = re.compile(r"ORDER BY[\s\S]*", re.IGNORECASE)
63
+ order_by_clause = re.search(pattern, sql)
64
+ if order_by_clause:
65
+ order_by_clause = order_by_clause.group(0)
66
+ # get all columns in the ORDER BY clause, by looking at the text between ORDER BY and the next semicolon, comma, or parantheses
67
+ pattern = re.compile(r"(?<=ORDER BY)(.*?)(?=;|,|\)|$)", re.IGNORECASE)
68
+ order_by_columns = re.findall(pattern, order_by_clause)
69
+ order_by_columns = (
70
+ order_by_columns[0].split() if order_by_columns else []
71
+ )
72
+ order_by_columns = [
73
+ col.strip().rsplit(".", 1)[-1] for col in order_by_columns
74
+ ]
75
+
76
+ ascending = False
77
+ # if there is a DESC or ASC in the ORDER BY clause, set the ascending to that
78
+ if "DESC" in [i.upper() for i in order_by_columns]:
79
+ ascending = False
80
+ elif "ASC" in [i.upper() for i in order_by_columns]:
81
+ ascending = True
82
+
83
+ # remove whitespace, commas, and parantheses
84
+ order_by_columns = [col.strip() for col in order_by_columns]
85
+ order_by_columns = [
86
+ col.replace(",", "").replace("(", "") for col in order_by_columns
87
+ ]
88
+ order_by_columns = [
89
+ i
90
+ for i in order_by_columns
91
+ if i.lower()
92
+ not in ["desc", "asc", "nulls", "last", "first", "limit"]
93
+ ]
94
+
95
+ # get all columns in sorted_df that are not in order_by_columns
96
+ other_columns = [
97
+ i for i in sorted_df.columns.tolist() if i not in order_by_columns
98
+ ]
99
+
100
+ # only choose order_by_columns that are in sorted_df
101
+ order_by_columns = [
102
+ i for i in order_by_columns if i in sorted_df.columns.tolist()
103
+ ]
104
+ sorted_df = sorted_df.sort_values(
105
+ by=order_by_columns + other_columns, ascending=ascending
106
+ )
107
+
108
+ sorted_df = sorted_df[other_columns + order_by_columns]
109
+
110
+ if not has_order_by:
111
+ # sort rows using values from first column to last
112
+ sorted_df = sorted_df.sort_values(by=list(sorted_df.columns))
113
+
114
+ # reset index
115
+ sorted_df = deduplicate_columns(sorted_df)
116
+ sorted_df = sorted_df.reset_index(drop=True)
117
+ return sorted_df
118
+
119
+
120
+ def compare_df(
121
+ df_gold: pd.DataFrame,
122
+ df_gen: pd.DataFrame,
123
+ query_category: str,
124
+ question: str,
125
+ query_gold: str = None,
126
+ query_gen: str = None,
127
+ ) -> bool:
128
+ """
129
+ Compares two dataframes and returns True if they are the same, else False.
130
+ query_gold and query_gen are the original queries that generated the respective dataframes.
131
+ """
132
+ # drop duplicates to ensure equivalence
133
+ if df_gen.empty or df_gold.empty:
134
+ return False
135
+ try:
136
+ is_equal = df_gold.values == df_gen.values
137
+ if is_equal.all():
138
+ return True
139
+ except:
140
+ try:
141
+ is_equal = df_gold.values == df_gen.values
142
+ if is_equal:
143
+ return True
144
+ except:
145
+ pass
146
+
147
+ pattern = re.compile(r"ORDER BY[\s\S]*", re.IGNORECASE)
148
+ is_order = re.search(pattern, query_gold)
149
+
150
+ df_gold = normalize_table(df_gold, query_category, is_order, query_gold)
151
+ df_gen = normalize_table(df_gen, query_category, is_order, query_gen)
152
+
153
+ # perform same checks again for normalized tables
154
+ if df_gold.shape != df_gen.shape:
155
+ return False
156
+ # fill NaNs with -99999 to handle NaNs in the dataframes for comparison
157
+ df_gen.fillna(-99999, inplace=True)
158
+ df_gold.fillna(-99999, inplace=True)
159
+ is_equal = df_gold.values == df_gen.values
160
+
161
+ try:
162
+ return is_equal.all()
163
+ except:
164
+ return is_equal
165
+
166
+
167
+ def subset_df(
168
+ df_sub: pd.DataFrame,
169
+ df_super: pd.DataFrame,
170
+ query_category: str,
171
+ question: str,
172
+ query_super: str = None,
173
+ query_sub: str = None,
174
+ verbose: bool = False,
175
+ ) -> bool:
176
+ """
177
+ Checks if df_sub is a subset of df_super.
178
+ """
179
+ if df_sub.empty and df_super.empty:
180
+ return True # handle cases for empty dataframes
181
+
182
+ if df_sub.empty:
183
+ return False
184
+
185
+ is_order = False
186
+ if query_sub:
187
+ pattern = re.compile(r"ORDER BY[\s\S]*", re.IGNORECASE)
188
+ is_order = re.search(pattern, query_sub)
189
+
190
+ # make a copy of df_super so we don't modify the original while keeping track of matches
191
+ df_super_temp = df_super.copy(deep=True)
192
+ matched_columns = []
193
+ df_sub = deduplicate_columns(df_sub)
194
+ df_super_temp = deduplicate_columns(df_super_temp)
195
+ for col_sub_name in df_sub.columns:
196
+ col_match = False
197
+ for col_super_name in df_super_temp.columns:
198
+ col_sub = df_sub[col_sub_name].sort_values().reset_index(drop=True)
199
+ col_super = (
200
+ df_super_temp[col_super_name].sort_values().reset_index(drop=True)
201
+ )
202
+
203
+ try:
204
+ assert_series_equal(
205
+ col_sub, col_super, check_dtype=False, check_names=False
206
+ )
207
+ col_match = True
208
+ matched_columns.append(col_super_name)
209
+ # remove col_super_name to prevent us from matching it again
210
+ df_super_temp = df_super_temp.drop(columns=[col_super_name])
211
+ break
212
+ except AssertionError:
213
+ continue
214
+
215
+ if not col_match:
216
+ if verbose:
217
+ print(f"no match for {col_sub_name}")
218
+ return False
219
+
220
+ df_sub_normalized = normalize_table(df_sub, query_category, is_order, query_sub)
221
+
222
+ # get matched columns from df_super, and rename them with columns from df_sub, then normalize
223
+ df_super_matched = df_super[matched_columns].rename(
224
+ columns=dict(zip(matched_columns, df_sub.columns))
225
+ )
226
+ df_super_matched = normalize_table(
227
+ df_super_matched, query_category, is_order, query_super
228
+ )
229
+
230
+ try:
231
+ assert_frame_equal(df_sub_normalized, df_super_matched, check_dtype=False)
232
+ return True
233
+ except AssertionError:
234
+ return False
235
+
236
+
237
+ def _check_df(
238
+ gt_df: pd.DataFrame, pre_df: pd.DataFrame, gt_sql: str, pre_sql: str
239
+ ) -> bool:
240
+ try:
241
+ if gt_df.empty or pre_df.empty:
242
+ return False
243
+ result = compare_df(gt_df, pre_df, "", "", gt_sql, pre_sql)
244
+ if result:
245
+ return True
246
+ result = subset_df(gt_df, pre_df, "", "", query_sub=gt_sql, query_super=pre_sql)
247
+ return result
248
+ except Exception as e:
249
+ return False
250
+
251
+
252
+ def check_df(
253
+ gt_df: pd.DataFrame, pre_df: pd.DataFrame, gt_sql: str, pre_sql: str
254
+ ) -> bool:
255
+ try:
256
+ res = func_timeout(10, _check_df, args=(gt_df, pre_df, gt_sql, pre_sql))
257
+ return res
258
+ except FunctionTimedOut as e:
259
+ return False
260
+ except Exception as e:
261
+ return False
utils/prompt.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABC, abstractmethod
2
+ from typing import Dict, Any, List, Tuple, Optional, Union
3
+
4
+
5
+ class AlpacaTemplate:
6
+ DEFAULT_SYSTEM = (
7
+ "Below is an instruction that describes a task. "
8
+ "Write a response that appropriately completes the request."
9
+ )
10
+
11
+ @classmethod
12
+ def template(
13
+ cls,
14
+ user_content: str,
15
+ system_content: Union[str, None] = None,
16
+ response: Union[str, None] = None,
17
+ ) -> str:
18
+ template: str = ""
19
+
20
+ if system_content:
21
+ template += f"{system_content}\n\n"
22
+ else:
23
+ template += f"{cls.DEFAULT_SYSTEM}\n\n"
24
+
25
+ template += f"### Instruction:\n{user_content}\n\n### Response:\n"
26
+ if response:
27
+ template += response
28
+
29
+ return template
30
+
31
+
32
+ class SftPrompt(ABC):
33
+ @classmethod
34
+ @abstractmethod
35
+ def prompt_user_content(cls, data: Dict[str, Any]) -> str:
36
+ pass
37
+
38
+ @classmethod
39
+ @abstractmethod
40
+ def prompt_system_content(cls, data: Dict[str, Any]) -> Optional[str]:
41
+ pass
42
+
43
+ @classmethod
44
+ @abstractmethod
45
+ def prompt_target(cls, sql: str) -> str:
46
+ pass
47
+
48
+ @classmethod
49
+ def prompt(cls, data: Dict[str, Any]) -> Tuple[str, Optional[str], str]:
50
+ user_content = cls.prompt_user_content(data)
51
+ system_content = cls.prompt_system_content(data)
52
+ if "spark_sql" in data:
53
+ target = cls.prompt_target(data["spark_sql"])
54
+ else:
55
+ target = None
56
+ return user_content, system_content, target
57
+
58
+
59
+ class SQLGeneratePrompt(SftPrompt):
60
+ @classmethod
61
+ def split_res(
62
+ cls, res: Union[str, List[str], None]
63
+ ) -> Union[str, List[Union[str, None]], None]:
64
+ if res == None:
65
+ return res
66
+ if isinstance(res, list):
67
+ for i in range(len(res)):
68
+ res[i] = cls.split_res(res[i])
69
+ return res
70
+ else:
71
+ res = res.strip()
72
+ if not (res.startswith("```sql") and res.endswith("```")):
73
+ return None
74
+ return res[6:-3].strip()
75
+
76
+ @classmethod
77
+ def compose_extra_task_desc(
78
+ cls,
79
+ hint: Union[str, None],
80
+ related_question_sqls: Union[List[Dict[str, str]], None],
81
+ ) -> str:
82
+ if not hint and not related_question_sqls:
83
+ return ""
84
+ elif hint and not related_question_sqls:
85
+ return (
86
+ "I provide generation hint, you can refer to it to help you generate.\n"
87
+ )
88
+ elif not hint and related_question_sqls:
89
+ return "I provide other user queries related to the user query with the corresponding Spark SQL queries, you can refer to them to help you generate.\n"
90
+ else:
91
+ return "I provide generation hint and other user queries related to the user query with the corresponding Spark SQL queries, you can refer to them to help you generate.\n"
92
+
93
+ @classmethod
94
+ def compose_hint_content(cls, hint: Union[str, None]) -> str:
95
+ if hint == None:
96
+ return ""
97
+ if len(hint) == 0:
98
+ return ""
99
+ hint = hint.strip()
100
+ content = (
101
+ "[BEGIN OF GENERATION HINT]\n" f"{hint}\n" "[END OF GENERATION HINT]\n" "\n"
102
+ )
103
+ return content
104
+
105
+ @classmethod
106
+ def compose_related_question_sqls_content(
107
+ cls, related_question_sqls: Union[List[Dict[str, str]], None]
108
+ ) -> str:
109
+ if related_question_sqls == None:
110
+ return ""
111
+ if len(related_question_sqls) == 0:
112
+ return ""
113
+ content = "[BEGIN OF RELATED QUERIES]\n"
114
+ for i, question_sql in enumerate(related_question_sqls):
115
+ question, sql = question_sql["question"], question_sql["spark_sql"]
116
+
117
+ question = question.strip()
118
+ question = question.replace("\n", " ")
119
+ sql = sql.strip()
120
+
121
+ sub_content = (
122
+ f"# Related Query {i+1}\n"
123
+ "## User Query\n"
124
+ f"`{question}`\n"
125
+ "## Spark SQL Query\n"
126
+ "```sql\n"
127
+ f"{sql}\n"
128
+ "```\n"
129
+ "\n"
130
+ )
131
+ content = content + sub_content
132
+ content = content.strip() + "\n"
133
+ content += "[END OF RELATED QUERIES]\n\n"
134
+ return content
135
+
136
+ @classmethod
137
+ def extract_table_schema(cls, user_content: str) -> str:
138
+ start_idx = user_content.find("[BEGIN OF TABLE SCHEMAS]") + len(
139
+ "[BEGIN OF TABLE SCHEMAS]"
140
+ )
141
+ end_idx = user_content.find("[END OF TABLE SCHEMAS]")
142
+ return user_content[start_idx:end_idx].strip()
143
+
144
+ @classmethod
145
+ def extract_user_query(cls, user_content: str) -> str:
146
+ start_idx = user_content.find("[BEGIN OF QUERY]\nUser Query: ") + len(
147
+ "[BEGIN OF QUERY]\nUser Query: "
148
+ )
149
+ end_idx = user_content.find("[END OF QUERY]")
150
+ return user_content[start_idx:end_idx].strip()
151
+
152
+ @classmethod
153
+ def extract_hint(cls, user_content: str) -> Union[str, None]:
154
+ start_idx = user_content.find("[BEGIN OF GENERATION HINT]") + len(
155
+ "[BEGIN OF GENERATION HINT]"
156
+ )
157
+ end_idx = user_content.find("[END OF GENERATION HINT]")
158
+ if end_idx == -1:
159
+ return None
160
+ return user_content[start_idx:end_idx].strip()
161
+
162
+ @classmethod
163
+ def extract_related_question_sqls(
164
+ cls, user_content: str
165
+ ) -> Union[List[Dict[str, str]], None]:
166
+ start_idx = user_content.find("[BEGIN OF RELATED QUERIES]") + len(
167
+ "[BEGIN OF RELATED QUERIES]"
168
+ )
169
+ end_idx = user_content.find("[END OF RELATED QUERIES]")
170
+ if end_idx == -1:
171
+ return None
172
+ related_question_sqls = user_content[start_idx:end_idx].strip().split("\n\n")
173
+ res = []
174
+ for question_sql in related_question_sqls:
175
+ question_start_idx = question_sql.find("`") + 1
176
+ question_end_idx = question_sql.find("`\n##")
177
+ question = question_sql[question_start_idx:question_end_idx]
178
+
179
+ sql_start_idx = question_sql.find("```sql\n") + 7
180
+ sql_end_idx = -3
181
+ sql = question_sql[sql_start_idx:sql_end_idx]
182
+ res.append({"question": question, "spark_sql": sql})
183
+ return res
184
+
185
+ @classmethod
186
+ def prompt_user_content(cls, data: Dict[str, Any]) -> str:
187
+ question, schema = data["question"].strip(), data["schema"].strip()
188
+ hint, related_question_sqls = (
189
+ data["hint"],
190
+ data["related_question_sqls"],
191
+ )
192
+ extra_task_desc = cls.compose_extra_task_desc(hint, related_question_sqls)
193
+ hint_content = cls.compose_hint_content(hint)
194
+ related_question_sqls_content = cls.compose_related_question_sqls_content(
195
+ related_question_sqls
196
+ )
197
+
198
+ user_content = (
199
+ "[BEGIN OF TASK INSTRUCTION]\n"
200
+ "You are an expert in composing Spark SQL queries. You are given a user query and a set of table schemas.\n"
201
+ "Based on the user query, you need to generate one Spark SQL query to achieve the purpose.\n"
202
+ f"{extra_task_desc}"
203
+ "[END OF TASK INSTRUCTION]\n"
204
+ "\n"
205
+ "[BEGIN OF TABLE SCHEMAS]\n"
206
+ f"{schema}\n"
207
+ "[END OF TABLE SCHEMAS]\n"
208
+ "\n"
209
+ f"{hint_content}"
210
+ f"{related_question_sqls_content}"
211
+ "[BEGIN OF FORMAT INSTRUCTION]\n"
212
+ "The output MUST strictly adhere to the following format, and NO other text MUST be included.\n"
213
+ "```sql\n"
214
+ "your output Spark SQL query\n"
215
+ "```\n"
216
+ "[END OF FORMAT INSTRUCTION]\n"
217
+ "\n"
218
+ "[BEGIN OF QUERY]\n"
219
+ f"User Query: {question}\n"
220
+ "[END OF QUERY]\n"
221
+ )
222
+
223
+ user_content = AlpacaTemplate.template(user_content)
224
+ return user_content
225
+
226
+ @classmethod
227
+ def prompt_system_content(cls, data: Dict[str, Any]) -> Union[str, None]:
228
+ return None
229
+
230
+ @classmethod
231
+ def prompt_target(cls, sql: Union[str, List[str]]) -> Union[str, List[str]]:
232
+ def map_func(tmp_sql: str) -> str:
233
+ tmp_sql = tmp_sql.strip()
234
+ tmp_sql = tmp_sql.strip(";")
235
+ tmp_sql = tmp_sql.strip()
236
+ tmp_sql += ";"
237
+ return "```sql\n" f"{tmp_sql}\n" "```"
238
+
239
+ if isinstance(sql, str):
240
+ target = map_func(sql)
241
+ else:
242
+ target = [map_func(_sql) for _sql in sql]
243
+
244
+ return target