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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Inference module -- load checkpoint tu HuggingFace va generate SQL tu model
|
| 3 |
+
input string. Ho tro day du catalog checkpoint cua du an (4 stage x 3
|
| 4 |
+
architecture = 12 model), nguoi dung TU CHON qua dropdown UI bang 1 model_id
|
| 5 |
+
duy nhat (xem MODEL_CATALOG) -- khong con phu thuoc cung mode du lieu dang
|
| 6 |
+
active (fixed/uploaded), vi cac checkpoint Stage 2/3 da verify hoat dong tot
|
| 7 |
+
tren CA HAI dang schema (Spider-style co PK/FK VA WikiSQL-style khong PK/FK,
|
| 8 |
+
xem ghi chu duoi).
|
| 9 |
+
|
| 10 |
+
model_id format: "{terminal_dataset}_stage{n}_{architecture}"
|
| 11 |
+
- terminal_dataset: dataset CUOI CUNG model duoc fine-tune tren (quyet dinh
|
| 12 |
+
quy uoc sinh SQL ma model da hoc, KHONG can trung voi schema dang dung).
|
| 13 |
+
- stage: 1 (train rieng le) | 2 (WikiSQL->Spider) | 3 (WikiSQL->Spider->BIRD)
|
| 14 |
+
|
| 15 |
+
Da verify thuc nghiem (2026-06-26): checkpoint Stage 2/3 (da tiep xuc Spider/
|
| 16 |
+
BIRD multi-column SELECT + GROUP BY) VAN sinh dung multi-column SELECT ngay ca
|
| 17 |
+
khi duoc dua schema dang WikiSQL (khong PK/FK, vd CSV upload) -- vd
|
| 18 |
+
"SELECT store_name, revenue FROM data_table". Day la ly do chinh de mo rong
|
| 19 |
+
catalog nay: checkpoint Stage 1 WikiSQL (terminal_dataset=wikisql) KHONG BAO
|
| 20 |
+
GIO sinh duoc 2 cot (gioi han cau truc cua chinh grammar WikiSQL, xem
|
| 21 |
+
visualizer.py/CLAUDE.md) -> khong the ra chart; Stage 2/3 thi co the, doi lai
|
| 22 |
+
do chinh xac cho cau don gian (SELECT 1 cot, WHERE) co the thap hon mot chut
|
| 23 |
+
so voi Stage 1 WikiSQL thuan (xem EM/EX tung checkpoint trong label).
|
| 24 |
+
|
| 25 |
+
Luu y dinh dang tokenizer KHONG nhat quan giua cac checkpoint trong du an nay
|
| 26 |
+
(mot so luu san tokenizer.json FAST, mot so chi co vocab.json/merges.txt SLOW)
|
| 27 |
+
-- PHAI tu phat hien dinh dang co san (_has_fast_tokenizer_file) thay vi
|
| 28 |
+
hardcode use_fast=True/False.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
import os
|
| 32 |
+
|
| 33 |
+
import torch
|
| 34 |
+
from huggingface_hub import snapshot_download
|
| 35 |
+
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
|
| 36 |
+
|
| 37 |
+
NUM_BEAMS = 4
|
| 38 |
+
|
| 39 |
+
ARCHITECTURE_NAMES = {"t5": "T5-base", "codet5": "CodeT5-base", "bart": "BART-base"}
|
| 40 |
+
|
| 41 |
+
# Moi entry: repo, ckpt, max_input/output_length, label (hien thi dropdown),
|
| 42 |
+
# stage (1/2/3), terminal_dataset ("wikisql"|"spider"|"bird" -- dataset CUOI
|
| 43 |
+
# CUNG model fine-tune tren, quyet dinh quy uoc quote khi post-process).
|
| 44 |
+
MODEL_CATALOG = {
|
| 45 |
+
# ---- Stage 1: train rieng le tren WikiSQL (EM greedy, in-training) ----
|
| 46 |
+
"wikisql_stage1_t5": {
|
| 47 |
+
"repo": "minimew/text2sql-checkpoints",
|
| 48 |
+
"ckpt": "wikisql/t5-base/run_6/epoch-12-em0_6918",
|
| 49 |
+
"max_input_length": 384, "max_output_length": 64,
|
| 50 |
+
"architecture": "t5", "stage": 1, "terminal_dataset": "wikisql",
|
| 51 |
+
"label": "T5-base 路 Stage 1 (WikiSQL)",
|
| 52 |
+
},
|
| 53 |
+
"wikisql_stage1_codet5": {
|
| 54 |
+
"repo": "minimew/text2sql-checkpoint-2",
|
| 55 |
+
"ckpt": "wikisql/codet5-base/run_1/epoch-08-em0_7688",
|
| 56 |
+
"max_input_length": 384, "max_output_length": 64,
|
| 57 |
+
"architecture": "codet5", "stage": 1, "terminal_dataset": "wikisql",
|
| 58 |
+
"label": "CodeT5-base 路 Stage 1 (WikiSQL)",
|
| 59 |
+
},
|
| 60 |
+
"wikisql_stage1_bart": {
|
| 61 |
+
"repo": "minimew/text2sql-checkpoints",
|
| 62 |
+
"ckpt": "wikisql/bart-base/run_1/epoch-05-em0_7228",
|
| 63 |
+
"max_input_length": 384, "max_output_length": 64,
|
| 64 |
+
"architecture": "bart", "stage": 1, "terminal_dataset": "wikisql",
|
| 65 |
+
"label": "BART-base 路 Stage 1 (WikiSQL)",
|
| 66 |
+
},
|
| 67 |
+
# ---- Stage 1: train rieng le tren Spider (EM/EX final eval, beam=4) ----
|
| 68 |
+
"spider_stage1_t5": {
|
| 69 |
+
"repo": "minimew/text2sql-checkpoints",
|
| 70 |
+
"ckpt": "spider/t5-base/run_5/epoch-07-em0_3956",
|
| 71 |
+
"max_input_length": 1024, "max_output_length": 128,
|
| 72 |
+
"architecture": "t5", "stage": 1, "terminal_dataset": "spider",
|
| 73 |
+
"label": "T5-base 路 Stage 1 (Spider)",
|
| 74 |
+
},
|
| 75 |
+
"spider_stage1_codet5": {
|
| 76 |
+
"repo": "minimew/text2sql-checkpoint-2",
|
| 77 |
+
"ckpt": "spider/codet5-base/run_1/epoch-07-em0_4391",
|
| 78 |
+
"max_input_length": 1024, "max_output_length": 128,
|
| 79 |
+
"architecture": "codet5", "stage": 1, "terminal_dataset": "spider",
|
| 80 |
+
"label": "CodeT5-base 路 Stage 1 (Spider)",
|
| 81 |
+
},
|
| 82 |
+
"spider_stage1_bart": {
|
| 83 |
+
"repo": "minimew/text2sql-checkpoints",
|
| 84 |
+
"ckpt": "spider/bart-base/run_1/epoch-08-em0_2940",
|
| 85 |
+
"max_input_length": 1024, "max_output_length": 128,
|
| 86 |
+
"architecture": "bart", "stage": 1, "terminal_dataset": "spider",
|
| 87 |
+
"label": "BART-base 路 Stage 1 (Spider)",
|
| 88 |
+
},
|
| 89 |
+
# ---- Stage 2: WikiSQL -> Spider (EM/EX final eval, beam=4) ----
|
| 90 |
+
# Da verify: van sinh dung multi-column SELECT tren schema kieu WikiSQL
|
| 91 |
+
# (CSV upload) -- lua chon tot nhat neu can chart tu CSV.
|
| 92 |
+
"spider_stage2_t5": {
|
| 93 |
+
"repo": "minimew/text2sql-checkpoints",
|
| 94 |
+
"ckpt": "stage2/spider/t5-base/run_1/epoch-08-em0_3752",
|
| 95 |
+
"max_input_length": 1024, "max_output_length": 128,
|
| 96 |
+
"architecture": "t5", "stage": 2, "terminal_dataset": "spider",
|
| 97 |
+
"label": "T5-base 路 Stage 2 (WikiSQL鈫扴pider)",
|
| 98 |
+
},
|
| 99 |
+
"spider_stage2_codet5": {
|
| 100 |
+
"repo": "minimew/text2sql-checkpoint-2",
|
| 101 |
+
"ckpt": "stage2/spider/codet5-base/run_1/epoch-07-em0_4275",
|
| 102 |
+
"max_input_length": 1024, "max_output_length": 128,
|
| 103 |
+
"architecture": "codet5", "stage": 2, "terminal_dataset": "spider",
|
| 104 |
+
"label": "CodeT5-base 路 Stage 2 (WikiSQL鈫扴pider)",
|
| 105 |
+
},
|
| 106 |
+
"spider_stage2_bart": {
|
| 107 |
+
"repo": "minimew/text2sql-checkpoints",
|
| 108 |
+
"ckpt": "stage2/spider/bart-base/run_1/epoch-07-em0_3037",
|
| 109 |
+
"max_input_length": 1024, "max_output_length": 128,
|
| 110 |
+
"architecture": "bart", "stage": 2, "terminal_dataset": "spider",
|
| 111 |
+
"label": "BART-base 路 Stage 2 (WikiSQL鈫扴pider)",
|
| 112 |
+
},
|
| 113 |
+
# ---- Stage 3: WikiSQL -> Spider -> BIRD (EX tren BIRD dev, final eval) ----
|
| 114 |
+
# Da verify: van sinh SQL hop le tren CA schema Spider va WikiSQL (khong
|
| 115 |
+
# can field "evidence:" -- demo nay khong co BIRD DB thuc/evidence injection).
|
| 116 |
+
"bird_stage3_t5": {
|
| 117 |
+
"repo": "minimew/text2sql-checkpoints",
|
| 118 |
+
"ckpt": "stage3/bird/t5-base/run_1/epoch-12-em0_0495",
|
| 119 |
+
"max_input_length": 1024, "max_output_length": 128,
|
| 120 |
+
"architecture": "t5", "stage": 3, "terminal_dataset": "bird",
|
| 121 |
+
"label": "T5-base 路 Stage 3 (鈫払IRD)",
|
| 122 |
+
},
|
| 123 |
+
"bird_stage3_codet5": {
|
| 124 |
+
"repo": "minimew/text2sql-checkpoint-2",
|
| 125 |
+
"ckpt": "stage3/bird/codet5-base/run_1/epoch-11-em0_1037",
|
| 126 |
+
"max_input_length": 1024, "max_output_length": 128,
|
| 127 |
+
"architecture": "codet5", "stage": 3, "terminal_dataset": "bird",
|
| 128 |
+
"label": "CodeT5-base 路 Stage 3 (鈫払IRD)",
|
| 129 |
+
},
|
| 130 |
+
"bird_stage3_bart": {
|
| 131 |
+
"repo": "minimew/text2sql-checkpoints",
|
| 132 |
+
"ckpt": "stage3/bird/bart-base/run_1/epoch-12-em0_0443",
|
| 133 |
+
"max_input_length": 1024, "max_output_length": 128,
|
| 134 |
+
"architecture": "bart", "stage": 3, "terminal_dataset": "bird",
|
| 135 |
+
"label": "BART-base 路 Stage 3 (鈫払IRD)",
|
| 136 |
+
},
|
| 137 |
+
# ---- Joint: train dong thoi WikiSQL + Spider + BIRD (40/40/20 mix) ----
|
| 138 |
+
# CodeT5 only (RQ5). Spider EX 60.74% / WikiSQL EX 81.89% / BIRD EX 23.08%.
|
| 139 |
+
# terminal_dataset="spider": 60% du lieu la Spider+BIRD dung single-quote
|
| 140 |
+
# cho string value -- ap dung quote normalization nhu cac checkpoint Spider.
|
| 141 |
+
"joint_codet5": {
|
| 142 |
+
"repo": "minimew/text2sql-checkpoint-2",
|
| 143 |
+
"ckpt": "joint/codet5-base/run_1/epoch-12-emavg0_4333",
|
| 144 |
+
"max_input_length": 1024, "max_output_length": 128,
|
| 145 |
+
"architecture": "codet5", "stage": "joint", "terminal_dataset": "spider",
|
| 146 |
+
"label": "CodeT5-base 路 Joint (WikiSQL + Spider + BIRD)",
|
| 147 |
+
},
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
DEFAULT_MODEL_ID_FOR_MODE = {
|
| 151 |
+
"fixed": "spider_stage1_codet5",
|
| 152 |
+
"uploaded": "wikisql_stage1_codet5",
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
_state = {}
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def _has_fast_tokenizer_file(ckpt_path: str) -> bool:
|
| 159 |
+
return os.path.exists(os.path.join(ckpt_path, "tokenizer.json"))
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def get_checkpoint_config(model_id: str) -> dict:
|
| 163 |
+
return MODEL_CATALOG[model_id]
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def load_model(model_id: str):
|
| 167 |
+
"""Load model + tokenizer cho 1 checkpoint, cache rieng theo model_id.
|
| 168 |
+
Goi lai voi cung model_id se tra ve doi tuong da cache."""
|
| 169 |
+
if model_id in _state:
|
| 170 |
+
return _state[model_id]["model"], _state[model_id]["tokenizer"], _state[model_id]["device"]
|
| 171 |
+
|
| 172 |
+
cfg = get_checkpoint_config(model_id)
|
| 173 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 174 |
+
|
| 175 |
+
# local_dir_use_symlinks=False: tranh OSError WinError 1314 tren Windows
|
| 176 |
+
# khi Developer Mode chua kich hoat (huggingface_hub mac dinh dung symlink
|
| 177 |
+
# de cache, can quyen dac biet de tao symlink tren Windows).
|
| 178 |
+
local_dir = snapshot_download(
|
| 179 |
+
repo_id=cfg["repo"], allow_patterns=[f"{cfg['ckpt']}/*"], local_dir_use_symlinks=False
|
| 180 |
+
)
|
| 181 |
+
ckpt_path = os.path.join(local_dir, cfg["ckpt"])
|
| 182 |
+
|
| 183 |
+
use_fast = _has_fast_tokenizer_file(ckpt_path)
|
| 184 |
+
tokenizer = AutoTokenizer.from_pretrained(ckpt_path, use_fast=use_fast)
|
| 185 |
+
model = AutoModelForSeq2SeqLM.from_pretrained(ckpt_path).to(device)
|
| 186 |
+
model.eval()
|
| 187 |
+
|
| 188 |
+
_state[model_id] = {"model": model, "tokenizer": tokenizer, "device": device}
|
| 189 |
+
return model, tokenizer, device
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def generate_sql(model_input: str, model_id: str) -> str:
|
| 193 |
+
"""model_input: full string 'question: ... | schema: ...'."""
|
| 194 |
+
model, tokenizer, device = load_model(model_id)
|
| 195 |
+
cfg = get_checkpoint_config(model_id)
|
| 196 |
+
|
| 197 |
+
inputs = tokenizer(
|
| 198 |
+
model_input,
|
| 199 |
+
return_tensors="pt",
|
| 200 |
+
truncation=True,
|
| 201 |
+
max_length=cfg["max_input_length"],
|
| 202 |
+
).to(device)
|
| 203 |
+
|
| 204 |
+
with torch.no_grad():
|
| 205 |
+
outputs = model.generate(
|
| 206 |
+
**inputs,
|
| 207 |
+
num_beams=NUM_BEAMS,
|
| 208 |
+
max_length=cfg["max_output_length"],
|
| 209 |
+
early_stopping=True,
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
sql = tokenizer.decode(outputs[0], skip_special_tokens=True).strip()
|
| 213 |
+
|
| 214 |
+
# Dong bo voi normalize convention da dung luc eval CHO SPIDER/BIRD: model
|
| 215 |
+
# doi khi sinh double-quote cho STRING VALUE ("France") nhung gold dung
|
| 216 |
+
# single-quote ('France') -- doi sang single-quote de tang ty le execute
|
| 217 |
+
# thanh cong. KHONG ap dung cho checkpoint terminal_dataset=wikisql: o
|
| 218 |
+
# format WikiSQL, double-quote dung de quote TEN COT (xem quote_column()
|
| 219 |
+
# trong process_wikisql.py), con string value 膽a dung single-quote san --
|
| 220 |
+
# thay the se bien ten cot co quote thanh string literal sai (vd
|
| 221 |
+
# "product name" -> 'product name' bi SQLite hieu thanh chuoi hang so
|
| 222 |
+
# thay vi tham chieu cot).
|
| 223 |
+
if cfg["terminal_dataset"] != "wikisql":
|
| 224 |
+
sql = sql.replace('"', "'")
|
| 225 |
+
return sql
|