NL2SQL進(jìn)階系列(1):DB-GPT-Hub、SQLcoder、Text2SQL開源應(yīng)用實(shí)踐詳解
NL2SQL基礎(chǔ)系列(1):業(yè)界頂尖排行榜、權(quán)威測評數(shù)據(jù)集及LLM大模型(Spider vs BIRD)全面對比優(yōu)劣分析[Text2SQL、Text2DSL]
NL2SQL基礎(chǔ)系列(2):主流大模型與微調(diào)方法精選集,Text2SQL經(jīng)典算法技術(shù)回顧七年發(fā)展脈絡(luò)梳理
1. MindSQL(庫)
MindSQL 是一個(gè) Python RAG(檢索增強(qiáng)生成)庫,旨在僅使用幾行代碼來簡化用戶與其數(shù)據(jù)庫之間的交互。 MindSQL 與 PostgreSQL、MySQL、SQLite 等知名數(shù)據(jù)庫無縫集成,還通過擴(kuò)展核心類,將其功能擴(kuò)展到 Snowflake、BigQuery 等主流數(shù)據(jù)庫。 該庫利用 GPT-4、Llama 2、Google Gemini 等大型語言模型 (LLM),并支持 ChromaDB 和 Fais 等知識庫。
官方鏈接:https://pypi.org/project/mindsql/
https://github.com/Mindinventory/MindSQL
- 使用案例
#!pip install mindsql
from mindsql.core import MindSQLCore
from mindsql.databases import Sqlite
from mindsql.llms import GoogleGenAi
from mindsql.vectorstores import ChromaDB
#Add Your Configurations
config = {"api_key": "YOUR-API-KEY"}
#Choose the Vector Store. LLM and DB You Want to Work With And
#Create MindSQLCore Instance With Configured Llm, Vectorstore, And Database
minds = MindSQLCore(
llm=GoogleGenAi(config=config),
vectorstore=ChromaDB(),
database=Sqlite()
)
#Create a Database Connection Using The Specified URL
connection = minds.database.create_connection(url="YOUR_DATABASE_CONNECTION_URL")
#Index All Data Definition Language (DDL) Statements in The Specified Database Into The Vectorstore
minds.index_all_ddls(connection=connection, db_name='NAME_OF_THE_DB')
#Index Question-Sql Pair in Bulk From the Specified Example Path
minds.index(bulk=True, path="your-qsn-sql-example.json")
#Ask a Question to The Database And Visualize The Result
response = minds.ask_db(
question="YOUR_QUESTION",
connection=connection,
visualize=True
)
#Extract And Display The Chart From The Response
chart = response["chart"]
chart.show()
#Close The Connection to Your DB
connection.close()
2.DB-GPT-Hub:利用LLMs實(shí)現(xiàn)Text-to-SQL微調(diào)
DB-GPT-Hub是一個(gè)利用LLMs實(shí)現(xiàn)Text-to-SQL解析的實(shí)驗(yàn)項(xiàng)目,主要包含數(shù)據(jù)集收集、數(shù)據(jù)預(yù)處理、模型選擇與構(gòu)建和微調(diào)權(quán)重等步驟,通過這一系列的處理可以在提高Text-to-SQL能力的同時(shí)降低模型訓(xùn)練成本,讓更多的開發(fā)者參與到Text-to-SQL的準(zhǔn)確度提升工作當(dāng)中,最終實(shí)現(xiàn)基于數(shù)據(jù)庫的自動(dòng)問答能力,讓用戶可以通過自然語言描述完成復(fù)雜數(shù)據(jù)庫的查詢操作等工作。
2.1、數(shù)據(jù)集
本項(xiàng)目案例數(shù)據(jù)主要以Spider數(shù)據(jù)集為示例 :
- Spider: 一個(gè)跨域的復(fù)雜text2sql數(shù)據(jù)集,包含了10,181條自然語言問句、分布在200個(gè)獨(dú)立數(shù)據(jù)庫中的5,693條SQL,內(nèi)容覆蓋了138個(gè)不同的領(lǐng)域。下載鏈接
其他數(shù)據(jù)集:
- WikiSQL: 一個(gè)大型的語義解析數(shù)據(jù)集,由80,654個(gè)自然語句表述和24,241張表格的sql標(biāo)注構(gòu)成。WikiSQL中每一個(gè)問句的查詢范圍僅限于同一張表,不包含排序、分組、子查詢等復(fù)雜操作。
- CHASE: 一個(gè)跨領(lǐng)域多輪交互text2sql中文數(shù)據(jù)集,包含5459個(gè)多輪問題組成的列表,一共17940個(gè)<query, SQL>二元組,涉及280個(gè)不同領(lǐng)域的數(shù)據(jù)庫。
- BIRD-SQL:數(shù)據(jù)集是一個(gè)英文的大規(guī)??珙I(lǐng)域文本到SQL基準(zhǔn)測試,特別關(guān)注大型數(shù)據(jù)庫內(nèi)容。該數(shù)據(jù)集包含12,751對文本到SQL數(shù)據(jù)對和95個(gè)數(shù)據(jù)庫,總大小為33.4GB,跨越37個(gè)職業(yè)領(lǐng)域。BIRD-SQL數(shù)據(jù)集通過探索三個(gè)額外的挑戰(zhàn),即處理大規(guī)模和混亂的數(shù)據(jù)庫值、外部知識推理和優(yōu)化SQL執(zhí)行效率,縮小了文本到SQL研究與實(shí)際應(yīng)用之間的差距。
- CoSQL:是一個(gè)用于構(gòu)建跨域?qū)υ捨谋镜絪ql系統(tǒng)的語料庫。它是Spider和SParC任務(wù)的對話版本。CoSQL由30k+回合和10k+帶注釋的SQL查詢組成,這些查詢來自Wizard-of-Oz的3k個(gè)對話集合,查詢了跨越138個(gè)領(lǐng)域的200個(gè)復(fù)雜數(shù)據(jù)庫。每個(gè)對話都模擬了一個(gè)真實(shí)的DB查詢場景,其中一個(gè)工作人員作為用戶探索數(shù)據(jù)庫,一個(gè)SQL專家使用SQL檢索答案,澄清模棱兩可的問題,或者以其他方式通知。
- 按照NSQL的處理模板,對數(shù)據(jù)集做簡單處理,共得到約20w條訓(xùn)練數(shù)據(jù)
2.2、基座模型
DB-GPT-HUB目前已經(jīng)支持的base模型有:
- CodeLlama
- Baichuan2
- LLaMa/LLaMa2
- Falcon
- Qwen
- XVERSE
- ChatGLM2
- ChatGLM3
- internlm
- Falcon
- sqlcoder-7b(mistral)
- sqlcoder2-15b(starcoder)
模型可以基于quantization_bit為4的量化微調(diào)(QLoRA)所需的最低硬件資源,可以參考如下:
模型參數(shù) | GPU RAM | CPU RAM | DISK |
---|---|---|---|
7b | 6GB | 3.6GB | 36.4GB |
13b | 13.4GB | 5.9GB | 60.2GB |
其中相關(guān)參數(shù)均設(shè)置的為最小,batch_size為1,max_length為512。根據(jù)經(jīng)驗(yàn),如果計(jì)算資源足夠,為了效果更好,建議相關(guān)長度值設(shè)置為1024或者2048。
2.3 快速使用
- 環(huán)境安裝
git clone https://github.com/eosphoros-ai/DB-GPT-Hub.git
cd DB-GPT-Hub
conda create -n dbgpt_hub python=3.10
conda activate dbgpt_hub
pip install poetry
poetry install
2.3.1 數(shù)據(jù)預(yù)處理
DB-GPT-Hub使用的是信息匹配生成法進(jìn)行數(shù)據(jù)準(zhǔn)備,即結(jié)合表信息的 SQL + Repository 生成方式,這種方式結(jié)合了數(shù)據(jù)表信息,能夠更好地理解數(shù)據(jù)表的結(jié)構(gòu)和關(guān)系,適用于生成符合需求的 SQL 語句。
從spider數(shù)據(jù)集鏈接 下載spider數(shù)據(jù)集,默認(rèn)將數(shù)據(jù)下載解壓后,放在目錄dbgpt_hub/data下面,即路徑為dbgpt_hub/data/spider
。
數(shù)據(jù)預(yù)處理部分,只需運(yùn)行如下腳本即可:
##生成train數(shù)據(jù) 和dev(eval)數(shù)據(jù),
poetry run sh dbgpt_hub/scripts/gen_train_eval_data.sh
在dbgpt_hub/data/
目錄你會(huì)得到新生成的訓(xùn)練文件example_text2sql_train.json 和測試文件example_text2sql_dev.json ,數(shù)據(jù)量分別為8659和1034條。 對于后面微調(diào)時(shí)的數(shù)據(jù)使用在dbgpt_hub/data/dataset_info.json中將參數(shù)file_name
值給為訓(xùn)練集的文件名,如example_text2sql_train.json。
生成的json中的數(shù)據(jù)形如:
{
"db_id": "department_management",
"instruction": "I want you to act as a SQL terminal in front of an example database, you need only to return the sql command to me.Below is an instruction that describes a task, Write a response that appropriately completes the request.\n\"\n##Instruction:\ndepartment_management contains tables such as department, head, management. Table department has columns such as Department_ID, Name, Creation, Ranking, Budget_in_Billions, Num_Employees. Department_ID is the primary key.\nTable head has columns such as head_ID, name, born_state, age. head_ID is the primary key.\nTable management has columns such as department_ID, head_ID, temporary_acting. department_ID is the primary key.\nThe head_ID of management is the foreign key of head_ID of head.\nThe department_ID of management is the foreign key of Department_ID of department.\n\n",
"input": "###Input:\nHow many heads of the departments are older than 56 ?\n\n###Response:",
"output": "SELECT count(*) FROM head WHERE age > 56",
"history": []
},
項(xiàng)目的數(shù)據(jù)處理代碼中已經(jīng)嵌套了chase
、cosql
、sparc
的數(shù)據(jù)處理,可以根據(jù)上面鏈接將數(shù)據(jù)集下載到data路徑后,在dbgpt_hub/configs/config.py
中將 SQL_DATA_INFO
中對應(yīng)的代碼注釋松開即可。
2.3.2 快速開始
首先,用如下命令安裝dbgpt-hub
:
pip install dbgpt-hub
然后,指定參數(shù)并用幾行代碼完成整個(gè)Text2SQL fine-tune流程:
from dbgpt_hub.data_process import preprocess_sft_data
from dbgpt_hub.train import start_sft
from dbgpt_hub.predict import start_predict
from dbgpt_hub.eval import start_evaluate
#配置訓(xùn)練和驗(yàn)證集路徑和參數(shù)
data_folder = "dbgpt_hub/data"
data_info = [
{
"data_source": "spider",
"train_file": ["train_spider.json", "train_others.json"],
"dev_file": ["dev.json"],
"tables_file": "tables.json",
"db_id_name": "db_id",
"is_multiple_turn": False,
"train_output": "spider_train.json",
"dev_output": "spider_dev.json",
}
]
#配置fine-tune參數(shù)
train_args = {
"model_name_or_path": "codellama/CodeLlama-13b-Instruct-hf",
"do_train": True,
"dataset": "example_text2sql_train",
"max_source_length": 2048,
"max_target_length": 512,
"finetuning_type": "lora",
"lora_target": "q_proj,v_proj",
"template": "llama2",
"lora_rank": 64,
"lora_alpha": 32,
"output_dir": "dbgpt_hub/output/adapter/CodeLlama-13b-sql-lora",
"overwrite_cache": True,
"overwrite_output_dir": True,
"per_device_train_batch_size": 1,
"gradient_accumulation_steps": 16,
"lr_scheduler_type": "cosine_with_restarts",
"logging_steps": 50,
"save_steps": 2000,
"learning_rate": 2e-4,
"num_train_epochs": 8,
"plot_loss": True,
"bf16": True,
}
#配置預(yù)測參數(shù)
predict_args = {
"model_name_or_path": "codellama/CodeLlama-13b-Instruct-hf",
"template": "llama2",
"finetuning_type": "lora",
"checkpoint_dir": "dbgpt_hub/output/adapter/CodeLlama-13b-sql-lora",
"predict_file_path": "dbgpt_hub/data/eval_data/dev_sql.json",
"predict_out_dir": "dbgpt_hub/output/",
"predicted_out_filename": "pred_sql.sql",
}
#配置評估參數(shù)
evaluate_args = {
"input": "./dbgpt_hub/output/pred/pred_sql_dev_skeleton.sql",
"gold": "./dbgpt_hub/data/eval_data/gold.txt",
"gold_natsql": "./dbgpt_hub/data/eval_data/gold_natsql2sql.txt",
"db": "./dbgpt_hub/data/spider/database",
"table": "./dbgpt_hub/data/eval_data/tables.json",
"table_natsql": "./dbgpt_hub/data/eval_data/tables_for_natsql2sql.json",
"etype": "exec",
"plug_value": True,
"keep_distict": False,
"progress_bar_for_each_datapoint": False,
"natsql": False,
}
#執(zhí)行整個(gè)Fine-tune流程
preprocess_sft_data(
data_folder = data_folder,
data_info = data_info
)
start_sft(train_args)
start_predict(predict_args)
start_evaluate(evaluate_args)
2.3.3、模型微調(diào)
本項(xiàng)目微調(diào)不僅能支持QLoRA和LoRA法,還支持deepseed。 可以運(yùn)行以下命令來微調(diào)模型,默認(rèn)帶著參數(shù)--quantization_bit
為QLoRA的微調(diào)方式,如果想要轉(zhuǎn)換為lora的微調(diào),只需在腳本中去掉quantization_bit參數(shù)即可。
默認(rèn)QLoRA微調(diào),運(yùn)行命令:
poetry run sh dbgpt_hub/scripts/train_sft.sh
微調(diào)后的模型權(quán)重會(huì)默認(rèn)保存到adapter文件夾下面,即dbgpt_hub/output/adapter目錄中。
如果使用多卡訓(xùn)練,想要用deepseed ,則將train_sft.sh中默認(rèn)的內(nèi)容進(jìn)行更改,
調(diào)整為:
CUDA_VISIBLE_DEVICES=0 python dbgpt_hub/train/sft_train.py \
--quantization_bit 4 \
...
更改為:
deepspeed --num_gpus 2 dbgpt_hub/train/sft_train.py \
--deepspeed dbgpt_hub/configs/ds_config.json \
--quantization_bit 4 \
...
如果需要指定對應(yīng)的顯卡id而不是默認(rèn)的前兩個(gè)如3,4,可以如下
deepspeed --include localhost:3,4 dbgpt_hub/train/sft_train.py \
--deepspeed dbgpt_hub/configs/ds_config.json \
--quantization_bit 4 \
...
其他省略(…)的部分均保持一致即可。 如果想要更改默認(rèn)的deepseed配置,進(jìn)入 dbgpt_hub/configs
目錄,在ds_config.json 更改即可,默認(rèn)為stage2的策略。
腳本中微調(diào)時(shí)不同模型對應(yīng)的關(guān)鍵參數(shù)lora_target 和 template,如下表:
模型名 | lora_target | template |
---|---|---|
LLaMA-2 | q_proj,v_proj | llama2 |
CodeLlama-2 | q_proj,v_proj | llama2 |
Baichuan2 | W_pack | baichuan2 |
Qwen | c_attn | chatml |
sqlcoder-7b | q_proj,v_proj | mistral |
sqlcoder2-15b | c_attn | default |
InternLM | q_proj,v_proj | intern |
XVERSE | q_proj,v_proj | xverse |
ChatGLM2 | query_key_value | chatglm2 |
LLaMA | q_proj,v_proj | - |
BLOOM | query_key_value | - |
BLOOMZ | query_key_value | - |
Baichuan | W_pack | baichuan |
Falcon | query_key_value | - |
train_sft.sh
中其他關(guān)鍵參數(shù)含義:
quantization_bit:是否量化,取值為[4或者8]
model_name_or_path: LLM模型的路徑
dataset: 取值為訓(xùn)練數(shù)據(jù)集的配置名字,對應(yīng)在dbgpt_hub/data/dataset_info.json 中外層key值,如example_text2sql。
max_source_length: 輸入模型的文本長度,如果計(jì)算資源支持,可以盡能設(shè)大,如1024或者2048。
max_target_length: 輸出模型的sql內(nèi)容長度,設(shè)置為512一般足夠。
output_dir : SFT微調(diào)時(shí)Peft模塊輸出的路徑,默認(rèn)設(shè)置在dbgpt_hub/output/adapter/路徑下 。
per_device_train_batch_size : batch的大小,如果計(jì)算資源支持,可以設(shè)置為更大,默認(rèn)為1。
gradient_accumulation_steps : 梯度更新的累計(jì)steps值
save_steps : 模型保存的ckpt的steps大小值,默認(rèn)可以設(shè)置為100。
num_train_epochs : 訓(xùn)練數(shù)據(jù)的epoch數(shù)
2.3.4、模型預(yù)測
項(xiàng)目目錄下./dbgpt_hub/
下的output/pred/
,此文件路徑為關(guān)于模型預(yù)測結(jié)果默認(rèn)輸出的位置(如果沒有則建上)。
預(yù)測運(yùn)行命令:
poetry run sh ./dbgpt_hub/scripts/predict_sft.sh
腳本中默認(rèn)帶著參數(shù)--quantization_bit
為QLoRA的預(yù)測,去掉即為LoRA的預(yù)測方式。
其中參數(shù)predicted_input_filename
為要預(yù)測的數(shù)據(jù)集文件, --predicted_out_filename
的值為模型預(yù)測的結(jié)果文件名。默認(rèn)結(jié)果保存在dbgpt_hub/output/pred
目錄。
2.3.5、模型權(quán)重
可以從Huggingface查看社區(qū)上傳的第二版Peft模塊權(quán)重huggingface地址 (202310) ,在spider評估集上的執(zhí)行準(zhǔn)確率達(dá)到0.789。
- 模型和微調(diào)權(quán)重合并
如果你需要將訓(xùn)練的基礎(chǔ)模型和微調(diào)的Peft模塊的權(quán)重合并,導(dǎo)出一個(gè)完整的模型。則運(yùn)行如下模型導(dǎo)出腳本:
poetry run sh ./dbgpt_hub/scripts/export_merge.sh
注意將腳本中的相關(guān)參數(shù)路徑值替換為你項(xiàng)目所對應(yīng)的路徑。
2.3.6、模型評估
對于模型在數(shù)據(jù)集上的效果評估,默認(rèn)為在spider
數(shù)據(jù)集上。
運(yùn)行以下命令來:
poetry run python dbgpt_hub/eval/evaluation.py --plug_value --input Your_model_pred_file
你可以在這里找到最新的評估和實(shí)驗(yàn)結(jié)果。
注意: 默認(rèn)的代碼中指向的數(shù)據(jù)庫為從Spider官方網(wǎng)站下載的大小為95M的database,如果你需要使用基于Spider的test-suite中的數(shù)據(jù)庫(大小1.27G),請先下載鏈接中的數(shù)據(jù)庫到自定義目錄,并在上述評估命令中增加參數(shù)和值,形如--db Your_download_db_path
。
2.4 小結(jié)
整個(gè)過程會(huì)分為三個(gè)階段:
-
階段一:
- 搭建基本框架,基于數(shù)個(gè)大模型打通從數(shù)據(jù)處理、模型SFT訓(xùn)練、預(yù)測輸出和評估的整個(gè)流程
現(xiàn)在支持
- CodeLlama
- Baichuan2
- LLaMa/LLaMa2
- Falcon
- Qwen
- XVERSE
- ChatGLM2
- ChatGLM3
- internlm
- sqlcoder-7b(mistral)
- sqlcoder2-15b(starcoder)
- 搭建基本框架,基于數(shù)個(gè)大模型打通從數(shù)據(jù)處理、模型SFT訓(xùn)練、預(yù)測輸出和評估的整個(gè)流程
-
階段二:
- 優(yōu)化模型效果,支持更多不同模型進(jìn)行不同方式的微調(diào)。
-
對
prompt
優(yōu)化 - 放出評估效果,和優(yōu)化后的還不錯(cuò)的模型,并且給出復(fù)現(xiàn)教程(見微信公眾號EosphorosAI)
-
階段三:
- 推理速度優(yōu)化提升
- 業(yè)務(wù)場景和中文效果針對性優(yōu)化提升
3.sqlcoder
官方鏈接:https://github.com/defog-ai/sqlcoder
Defog組織提出的先進(jìn)的Text-to-SQL的大模型,表現(xiàn)亮眼,效果優(yōu)于GPT3.5、wizardcoder和starcoder等,僅次于GPT4。
將每個(gè)生成的問題分為6類。該表顯示了每個(gè)模型正確回答問題的百分比,并按類別進(jìn)行了細(xì)分。
4.modal_finetune_sql
項(xiàng)目基于LLaMa 2 7b模型進(jìn)行Text-to-SQL微調(diào),有完整的訓(xùn)練、微調(diào)、評估流程。
鏈接:https://github.com/run-llama/modal_finetune_sql
5.LLaMA-Efficient-Tuning
這是一個(gè)易于使用的LLM微調(diào)框架,支持LLaMA-2、BLOOM、Falcon、Baichuan、Qwen、ChatGLM2等。
鏈接:https://github.com/hiyouga/LLaMA-Factory/tree/main
- 多種模型:LLaMA、Mistral、Mixtral-MoE、Qwen、Yi、Gemma、Baichuan、ChatGLM、Phi 等等。
- 集成方法:(增量)預(yù)訓(xùn)練、指令監(jiān)督微調(diào)、獎(jiǎng)勵(lì)模型訓(xùn)練、PPO 訓(xùn)練、DPO 訓(xùn)練和 ORPO 訓(xùn)練。
- 多種精度:32 比特全參數(shù)微調(diào)、16 比特凍結(jié)微調(diào)、16 比特 LoRA 微調(diào)和基于 AQLM/AWQ/GPTQ/LLM.int8 的 2/4/8 比特 QLoRA 微調(diào)。
- 先進(jìn)算法:GaLore、DoRA、LongLoRA、LLaMA Pro、LoRA+、LoftQ 和 Agent 微調(diào)。
- 實(shí)用技巧:FlashAttention-2、Unsloth、RoPE scaling、NEFTune 和 rsLoRA。
- 實(shí)驗(yàn)監(jiān)控:LlamaBoard、TensorBoard、Wandb、MLflow 等等。
- 極速推理:基于 vLLM 的 OpenAI 風(fēng)格 API、瀏覽器界面和命令行接口。
- 訓(xùn)練方法
方法 | 全參數(shù)訓(xùn)練 | 部分參數(shù)訓(xùn)練 | LoRA | QLoRA |
---|---|---|---|---|
預(yù)訓(xùn)練 | ? | ? | ? | ? |
指令監(jiān)督微調(diào) | ? | ? | ? | ? |
獎(jiǎng)勵(lì)模型訓(xùn)練 | ? | ? | ? | ? |
PPO 訓(xùn)練 | ? | ? | ? | ? |
DPO 訓(xùn)練 | ? | ? | ? | ? |
ORPO 訓(xùn)練 | ? | ? | ? | ? |
- 可視化使用教學(xué)
https://github.com/hiyouga/LLaMA-Factory/assets/16256802/ec36a9dd-37f4-4f72-81bd-d76c6d0a6594
-
參考鏈接
-
Awesome Text2SQL:https://github.com/eosphoros-ai/Awesome-Text2SQL/blob/main/README.zh.md文章來源:http://www.zghlxwxcb.cn/news/detail-860069.html
更多優(yōu)質(zhì)內(nèi)容請關(guān)注公號:汀丶人工智能;會(huì)提供一些相關(guān)的資源和優(yōu)質(zhì)文章,免費(fèi)獲取閱讀。文章來源地址http://www.zghlxwxcb.cn/news/detail-860069.html
到了這里,關(guān)于NL2SQL進(jìn)階系列(1):DB-GPT-Hub、SQLcoder、Text2SQL開源應(yīng)用實(shí)踐詳解的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!