Text Generation
PEFT
Safetensors
MLX
English
text-to-sql
sql
sqlite
lora
bird
spider
Eval Results (legacy)
Nafize commited on
Commit
d2bec35
·
verified ·
1 Parent(s): 8caa87f

SQLant-1B: PEFT + MLX adapters (generator, verifier3), pipeline code, model card

Browse files
README.md ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ base_model: Qwen/Qwen2.5-Coder-1.5B-Instruct
4
+ library_name: peft
5
+ pipeline_tag: text-generation
6
+ language:
7
+ - en
8
+ tags:
9
+ - text-to-sql
10
+ - sql
11
+ - sqlite
12
+ - lora
13
+ - peft
14
+ - mlx
15
+ - bird
16
+ - spider
17
+ datasets:
18
+ - xlangai/spider
19
+ - seeklhy/SynSQL-2.5M
20
+ model-index:
21
+ - name: SQLant-1B
22
+ results:
23
+ - task:
24
+ type: text-to-sql
25
+ dataset:
26
+ name: BIRD dev (1,534 questions)
27
+ type: bird
28
+ split: dev
29
+ metrics:
30
+ - type: execution_accuracy
31
+ value: 55.7
32
+ name: EX (full pipeline, 8 candidates + verifier + value snapping)
33
+ - type: execution_accuracy
34
+ value: 44.9
35
+ name: EX (single answer, pruning + repair)
36
+ - task:
37
+ type: text-to-sql
38
+ dataset:
39
+ name: Spider dev (1,034 questions)
40
+ type: spider
41
+ split: dev
42
+ metrics:
43
+ - type: execution_accuracy
44
+ value: 76.0
45
+ name: EX (full pipeline, 8 candidates + verifier + value snapping)
46
+ - type: execution_accuracy
47
+ value: 74.7
48
+ name: EX (single answer, pruning + repair)
49
+ ---
50
+
51
+ # SQLant-1B
52
+
53
+ SQLant-1B is a small text-to-SQL system for **SQLite**. Given a database schema, an optional hint, and a question in English, it writes one SQL query that answers the question. It runs locally: with PyTorch (`transformers` + `peft`, on CUDA, Apple MPS or CPU) or with MLX on Apple Silicon. It was developed on an Apple M5 Pro with 24 GB.
54
+
55
+ It is made of two LoRA adapters on the same base model, [`Qwen/Qwen2.5-Coder-1.5B-Instruct`](https://huggingface.co/Qwen/Qwen2.5-Coder-1.5B-Instruct), plus a small amount of non-learned code:
56
+
57
+ | Component | What it does | Size |
58
+ |---|---|---|
59
+ | **Generator** (`generator/`) | Writes SQL from the schema and question | LoRA, rank 16, 68 MB |
60
+ | **Verifier** (`verifier/`) | Reads one candidate SQL and its first result rows, and answers "yes" or "no" to "is this correct?" | LoRA, rank 16, 68 MB |
61
+ | Schema pruning, SQL repair, value snapping | Non-learned code (`code/`): shrinks the prompt to relevant tables, fixes wrong table aliases and missing joins, corrects literal spellings | — |
62
+
63
+ ```
64
+ sqlant-1b/
65
+ ├── README.md
66
+ ├── generator/ adapter_config.json, adapter_model.safetensors (PEFT LoRA, layers 1–27)
67
+ ├── verifier/ adapter_config.json, adapter_model.safetensors (PEFT LoRA, layers 1–27)
68
+ ├── mlx/generator/ adapter_config.json, adapters.safetensors (same weights, MLX format)
69
+ ├── mlx/verifier/ adapter_config.json, adapters.safetensors
70
+ └── code/ full pipeline: run.py (BIRD-format runner), sqlant/ (pruning, repair, prompts, selection)
71
+ ```
72
+
73
+ The base model is not included; it downloads from Hugging Face on first use. Both adapters are loaded on **one** copy of the base and switched at runtime, so the whole system is 1.54B + 2 × 18M parameters.
74
+
75
+ "1B" is the size class. The base model has 1.54B parameters (1.31B without embeddings).
76
+
77
+ ## Results
78
+
79
+ Execution accuracy (EX) on the **full** BIRD dev (1,534) and Spider dev (1,034) sets. No dev question or database was used for training. Each configuration below was fixed beforehand and run on dev once, with one exception, noted in the last row: the choice between two verifiers was made on dev by a rule set before the run.
80
+
81
+ | Configuration | BIRD dev | Spider dev | Generations per question |
82
+ |---|---|---|---|
83
+ | Base model, no fine-tuning | 29.5 | 65.4 | 1 |
84
+ | Generator, single answer | 40.8 | 73.4 | 1 |
85
+ | Generator + schema pruning + SQL repair | 44.9 | 74.7 | 2 |
86
+ | + 8 candidates, majority vote on results | 51.2 | 75.4 | 9 |
87
+ | + verifier rerank | 53.3 (95% CI 50.8–55.7) | 77.2 (74.5–79.6) | 9, plus ~2.3 verifier passes |
88
+ | + value snapping + empty-result rule | 54.1 (51.6–56.6) | 74.8 (72.1–77.4) | same |
89
+ | **+ verifier trained on twice the data (full SQLant-1B pipeline)** | **55.7** (53.2–58.1) | **76.0** (73.3–78.5) | same |
90
+
91
+ - **The verifier is a statistically significant gain.** Against the plain vote it fixes 70 questions and breaks 21 (McNemar p < 0.001). The gain holds on both BIRD (44 / 13) and Spider (26 / 8).
92
+ - **Value snapping + the empty-result rule add 0.8 on BIRD** (14 questions fixed, 1 broken).
93
+ - **The final verifier was trained on twice the data** (19,491 examples, up from 9,395). On full dev it fixes 66 questions and breaks 28 (p < 0.001): BIRD +42/−17, Spider +24/−11. On held-out databases its gain was smaller (+23/−15, not significant), so it was chosen on dev by a rule set before the run: adopt it only if overall dev EX rose by at least 1.0 point. It rose by 1.5. Because the choice used dev, treat these dev numbers as slightly optimistic.
94
+ - **The lower Spider score is caused by one database with wrong gold answers.** 25 of the 27 lost Spider questions are in `flight_2`, whose stored values carry stray spaces (`'Anthony '`, `' APG'`). Spider's gold SQL compares against `"Anthony"`, so the gold answer is empty. SQLant's snapped SQL uses the stored value and returns the real rows, which the benchmark counts as wrong. On the other Spider databases the score is unchanged (76.2 → 76.2) by snapping, and the final pipeline scores 77.5 there. We kept the behaviour that gives correct answers on real data.
95
+ - **BIRD by difficulty** (full pipeline): simple 63.0 · moderate 46.8 · challenging 37.9.
96
+ - **Oracle@8** (at least one of the 8 candidates is correct): BIRD 64.9 / Spider 86.2, so better selection still has room to help.
97
+ - **PyTorch and MLX give the same system.** The results above were produced with MLX. The PyTorch/PEFT version in `code/` was checked against it on 200 BIRD dev questions: the verifier gives near-identical scores to the same inputs (correlation 0.9992, same top-ranked candidate in 40/40 questions), and 180/200 greedy drafts are identical (the rest differ through bf16 rounding). End-to-end accuracy differs only by sampling noise (34.0 vs 38.5 vs 35.5 for the original run, all differences not significant), because the two frameworks draw different random samples.
98
+
99
+ ### Comparison with published models (BIRD dev EX)
100
+
101
+ Other systems' numbers come from their papers and model cards, with their own prompts and setups, so differences of 1–2 points mean little.
102
+
103
+ | Model | Size | BIRD dev | Spider dev |
104
+ |---|---|---|---|
105
+ | Prem-1B-SQL | 1.3B | 46 | 85 |
106
+ | CodeS-1B (SFT) | 1B | 50.5 | 77.9 |
107
+ | **SQLant-1B (this model)** | 1.5B | **55.7** | **76.0**¹ |
108
+ | SLM-SQL-0.5B | 0.5B | 56.9 | — |
109
+ | OmniSQL-7B | 7B | 63.9 (66.1 with voting) | 81.2² |
110
+ | SLM-SQL-1.5B (same base, SFT + GRPO + voting) | 1.5B | 67.1 | — |
111
+
112
+ ¹ 77.5 without `flight_2`, whose gold answers are empty because of whitespace in the stored values (see above).
113
+ ² Test-suite accuracy, which is stricter than the execution accuracy in the other rows, so it is not directly comparable.
114
+
115
+ SQLant-1B uses only supervised fine-tuning plus inference-time selection; it has no reinforcement learning. Models with GRPO-style training on the same base score substantially higher on BIRD.
116
+
117
+ ## How it works
118
+
119
+ For each question:
120
+
121
+ 1. **Draft.** The generator writes one query (greedy) from the full schema.
122
+ 2. **Prune.** The schema is cut to the tables that matter: tables whose names or columns match the question or hint, tables containing values mentioned in the question, tables the draft used, and the foreign-key tables that connect them. Databases with fewer than 5 tables aren't pruned.
123
+ 3. **Generate 8 candidates.** On the pruned prompt: 1 greedy answer plus 7 samples (temperature 0.8, top-p 0.95).
124
+ 4. **Repair and run.** Each candidate is repaired (a column on the wrong alias, or a missing one-hop join along a foreign key, only when there is exactly one valid fix), then **value-snapped**: a literal in `col = '…'` that doesn't occur in that column is replaced by the unique stored value that matches it up to case, punctuation or spacing, or a short prefix for numbers (`2002` → `'YR2002'`). `col IS NULL` becomes `col = ''` when the column has no NULLs but has empty strings. The query is then executed read-only. Failed queries are dropped.
125
+ 5. **Group** the candidates by their result rows.
126
+ 6. **Verify.** If there are two or more groups, the verifier scores one SQL per group: `v = logit("yes") − logit("no")`, one forward pass, no generation.
127
+ 7. **Pick** the group with the highest `v + 1.5 · log(votes)`. A clear majority usually wins, and the verifier decides close calls. **If the chosen query returns no rows** and another group returns rows, the best such group is taken instead. If every candidate fails, the greedy answer is returned.
128
+
129
+ ### Prompt formats
130
+
131
+ **Generator.** One user turn in Qwen's chat template:
132
+
133
+ ~~~text
134
+ You are an expert SQLite developer who writes correct, efficient SQL.
135
+
136
+ Database schema (SQLite):
137
+ CREATE TABLE ... ; -- one block per (kept) table
138
+ /* 3 example rows from <table>:
139
+ col1 | col2 | ...
140
+ ... */
141
+
142
+ External knowledge: <hint> (omit the line if there is no hint)
143
+
144
+ Question: <question>
145
+
146
+ Write one SQLite query that answers the question. Return only the SQL inside a ```sql code block, with no explanation.
147
+ ~~~
148
+
149
+ **Verifier.** One user turn; it answers the single token `yes` or `no`:
150
+
151
+ ~~~text
152
+ You are an expert SQLite reviewer. Decide whether the candidate SQL correctly answers the question.
153
+
154
+ Database schema (SQLite):
155
+ <same pruned schema>
156
+
157
+ External knowledge: <hint>
158
+
159
+ Question: <question>
160
+
161
+ Candidate SQL:
162
+ ```sql
163
+ <repaired SQL>
164
+ ```
165
+
166
+ Execution result (first rows):
167
+ <up to 5 rows, " | "-separated, cells cut at 60 characters>
168
+ (<N> rows) or "... (<N> rows in total)" or "(no rows)"
169
+
170
+ Is the candidate SQL correct? Answer yes or no.
171
+ ~~~
172
+
173
+ ## Usage
174
+
175
+ ### Full pipeline (PyTorch or MLX)
176
+
177
+ ```bash
178
+ huggingface-cli download Felamity-Technologies/sqlant-1b --local-dir sqlant-1b
179
+ cd sqlant-1b/code
180
+ pip install -r requirements.txt # PyTorch backend; add mlx-lm for --backend mlx
181
+ python run.py --data dev.json --db_root dev_databases --out predict_dev.json
182
+ ```
183
+
184
+ The input is a BIRD-style JSON list with `question`, `evidence` (optional hint) and `db_id`; databases are read from `<db_root>/<db_id>/<db_id>.sqlite`. The output maps each question's index to `"<SQL>\t----- bird -----\t<db_id>"`. Progress is saved after every question, and re-running the same command resumes. Peak memory is about 5 GB.
185
+
186
+ ### PyTorch: loading the adapters
187
+
188
+ ```python
189
+ import torch
190
+ from peft import PeftModel
191
+ from transformers import AutoModelForCausalLM, AutoTokenizer
192
+
193
+ BASE, REPO = "Qwen/Qwen2.5-Coder-1.5B-Instruct", "Felamity-Technologies/sqlant-1b"
194
+ tok = AutoTokenizer.from_pretrained(BASE)
195
+ model = AutoModelForCausalLM.from_pretrained(BASE, torch_dtype=torch.bfloat16)
196
+ model = PeftModel.from_pretrained(model, REPO, subfolder="generator", adapter_name="generator")
197
+ model.load_adapter(REPO, subfolder="verifier", adapter_name="verifier")
198
+ model.set_adapter("generator") # or "verifier"
199
+ ```
200
+
201
+ When generating, pass `repetition_penalty=1.0` and `top_k=0`. The base model's `generation_config.json` otherwise applies `repetition_penalty=1.1` and `top_k=20`, which were not used in training or evaluation.
202
+
203
+ ### MLX
204
+
205
+ ```bash
206
+ pip install mlx-lm
207
+ ```
208
+
209
+ **Single answer** (generator only):
210
+
211
+ ```python
212
+ from mlx_lm import load, generate
213
+
214
+ SYSTEM = "You are an expert SQLite developer who writes correct, efficient SQL."
215
+ model, tok = load("Qwen/Qwen2.5-Coder-1.5B-Instruct", adapter_path="sqlant-1b/mlx/generator")
216
+
217
+ user = (f"{SYSTEM}\n\nDatabase schema (SQLite):\n{schema}\n\n"
218
+ + (f"External knowledge: {hint}\n\n" if hint else "")
219
+ + f"Question: {question}\n\n"
220
+ "Write one SQLite query that answers the question. "
221
+ "Return only the SQL inside a ```sql code block, with no explanation.")
222
+ ids = tok.apply_chat_template([{"role": "user", "content": user}], add_generation_prompt=True)
223
+ print(generate(model, tok, prompt=ids, max_tokens=512))
224
+ ```
225
+
226
+ **Scoring one candidate with the verifier:**
227
+
228
+ ```python
229
+ import mlx.core as mx
230
+ from mlx_lm import load
231
+
232
+ vmodel, vtok = load("Qwen/Qwen2.5-Coder-1.5B-Instruct", adapter_path="sqlant-1b/mlx/verifier")
233
+ yes, no = vtok.encode("yes")[0], vtok.encode("no")[0]
234
+ ids = vtok.apply_chat_template([{"role": "user", "content": verifier_prompt}], add_generation_prompt=True)
235
+ logits = vmodel(mx.array([ids]))[0, -1]
236
+ score = (logits[yes] - logits[no]).item() # higher = more likely correct
237
+ ```
238
+
239
+ The full pipeline is in `code/`:
240
+ - schema pruning, repair and value snapping: `code/sqlant/schema_tools.py`;
241
+ - prompt format: `code/sqlant/schema_format.py`;
242
+ - candidates, execution, grouping and verifier selection: `code/sqlant/pipeline.py`;
243
+ - backends: `code/sqlant/backend_torch.py` and `code/sqlant/backend_mlx.py`.
244
+
245
+ To get a standalone generator model, fuse the adapter: `python -m mlx_lm fuse --model Qwen/Qwen2.5-Coder-1.5B-Instruct --adapter-path sqlant-1b/mlx/generator --save-path sqlant-1b-generator`, or `merge_and_unload()` in PEFT. Don't fuse both adapters into one model; they are separate tasks.
246
+
247
+ ## Training
248
+
249
+ ### Generator
250
+
251
+ | | |
252
+ |---|---|
253
+ | Method | LoRA SFT, rank 16, scale 1.0, dropout 0.05, all 7 linear projections on transformer layers 1–27. Loss on the SQL answer only. |
254
+ | Data | 9,410 examples: the first 5 of 8 balanced shards of a 15,056-example set from **BIRD train** (7,287) and **Spider train** (7,769). Every gold query was execution-checked. 21 training databases were held out as a tuning set. No dev data. |
255
+ | Optimisation | AdamW, peak LR 1e-5, 50-update warmup, cosine schedule; stopped after 1,180 updates (effective batch 8). Gradient clipping 1.0. |
256
+ | Checkpoint choice | Best of 8 shards on the tuning set (300 questions from held-out training databases) |
257
+ | Hardware / time | Apple M5 Pro 24 GB, MLX bf16 with fp32 attention; about 3 hours |
258
+
259
+ ### Verifier
260
+
261
+ | | |
262
+ |---|---|
263
+ | Method | A separate LoRA (rank 16, layers 1–27, all 7 projections) on the base model, trained to answer `yes` / `no` |
264
+ | Data | The generator's own candidates (8 per question) on 10,458 questions: 3,484 BIRD-train and 2,974 Spider-train questions the generator never trained on, plus 4,000 **SynSQL-2.5M** questions. Labels come from executing each candidate against the gold query. 19,491 training examples (32% yes); 10% of databases held out for validation and for picking the 1.5 vote weight. |
265
+ | Optimisation | AdamW, LR 1e-4 → 1e-5 (linear), 1 epoch (2,437 updates, effective batch 8), clipping 1.0 |
266
+ | Hardware / time | Apple M5 Pro 24 GB; about 16 h to generate candidates + 9.2 h to train |
267
+
268
+ ### Training notes for MLX users
269
+
270
+ Three issues in mlx-lm 0.32.2 / mlx 0.32.4 silently broke LoRA training on this base model. Each looked like "the method doesn't help":
271
+
272
+ 1. **Loss mask off by one.** The default loss also trains on one padding token after each answer, which is ruinous for one-token targets.
273
+ 2. **Layer-0 gradients explode** (1e12+) in bf16 on Qwen2.5's q/k/v LoRA. With gradient clipping this silently zeroes all updates. Fix: skip layer 0.
274
+ 3. **bf16 attention backward gives noisy gradients**, which makes training drift after about 700 updates at any learning rate. Fix: compute attention in fp32 (same speed, fits in 24 GB).
275
+
276
+ ## Evaluation protocol
277
+
278
+ | | |
279
+ |---|---|
280
+ | Metric | Execution accuracy: the predicted query's result rows, compared as a **set** with the gold query's rows (like BIRD's official evaluator, which ignores row order and duplicates). 30 s timeout per query, read-only database. |
281
+ | Prompt | Schema as `CREATE TABLE` statements with 3 example rows per table (values cut at 40 characters), BIRD's hint text, the question |
282
+ | Decoding | Greedy for the draft and for candidate 1; T 0.8, top-p 0.95 for the 7 sampled candidates; max 512 new tokens |
283
+ | Selection hygiene | Every choice (pruning, repair, value snapping, the empty-result rule, number of candidates, verifier weight) was made on a tuning set from held-out training databases or on held-out-database verifier data. Dev was used once per milestone, for reporting only, except for the final choice between two verifiers (see Results). |
284
+
285
+ The Spider numbers use the same set-based comparison, not Spider's official test-suite evaluation, which also checks row order for `ORDER BY` queries. They may read slightly higher than official Spider EX.
286
+
287
+ ## Limitations
288
+
289
+ - **SQLite only, English only.** Trained and evaluated on SQLite dialect and English questions. Other dialects (Postgres, BigQuery, Snowflake) were not tested.
290
+ - **Benchmark-style data.** Training data comes from BIRD, Spider and synthetic SynSQL databases. Real enterprise schemas (hundreds of tables, cryptic names, no hints) will be harder; Spider 2.0-style warehouse tasks are out of scope.
291
+ - **About 44% of BIRD questions are still answered wrong.** Typical errors: a column taken from the wrong table, a wrong join path, a misread hint, and multi-step logic on "challenging" questions (37.9%). An audit of the tuning set found that about 1 in 10 BIRD gold queries is itself wrong or ambiguous, so the reachable ceiling is below 100%.
292
+ - **The full pipeline needs database access.** It executes candidate queries, so it needs a live (read-only) connection. Without one, use the single-answer mode (44.9 / 74.7 with pruning and repair, or 40.8 / 73.4 plain).
293
+ - **Harder, hint-free questions score much lower.** On the 2026 revision of BIRD mini-dev (SQLite, 500 questions, 460 of them "challenging", no hints), the full pipeline scores 4.6 EX, and at least one of the 8 candidates is correct for only 7.4%. About 22% of greedy answers there reference columns that don't exist. SQLant relies heavily on BIRD's hint text.
294
+ - **Cost.** The full pipeline runs about 9 generations per question plus ~2 verifier passes: about 10–13 s per question on an M5 Pro, with either backend.
295
+ - **The verifier's score is not a calibrated probability.** It's used only to rank candidates against each other.
296
+
297
+ ## Safe use
298
+
299
+ SQLant-1B writes SQL that the pipeline **executes**. Always run generated queries with a **read-only** connection or on a copy of the database. The pipeline itself never writes, but a model can produce `UPDATE`/`DELETE`/`DROP` if asked. Review queries before running them on data you care about, and don't use it as the only safeguard for access control.
300
+
301
+ ## Licence and data
302
+
303
+ - **Adapters:** Apache 2.0, the same as the base model [Qwen2.5-Coder-1.5B-Instruct](https://huggingface.co/Qwen/Qwen2.5-Coder-1.5B-Instruct).
304
+ - **Training data:**
305
+ - [BIRD](https://bird-bench.github.io) train: CC BY-SA 4.0.
306
+ - [Spider](https://yale-lily.github.io/spider) train: CC BY-SA 4.0.
307
+ - [SynSQL-2.5M](https://huggingface.co/datasets/seeklhy/SynSQL-2.5M) (OmniSQL), verifier only: Apache 2.0 per the OmniSQL release.
308
+
309
+ Check these licences against your intended use.
310
+
311
+ ## References
312
+
313
+ - Qwen2.5-Coder: [Qwen/Qwen2.5-Coder-1.5B-Instruct](https://huggingface.co/Qwen/Qwen2.5-Coder-1.5B-Instruct)
314
+ - BIRD: Li et al., *Can LLM Already Serve as A Database Interface? A BIg Bench for Large-Scale Database Grounded Text-to-SQLs*, [arXiv 2305.03111](https://arxiv.org/abs/2305.03111)
315
+ - Spider: Yu et al., *Spider: A Large-Scale Human-Labeled Dataset for Complex and Cross-Domain Semantic Parsing and Text-to-SQL Task*, EMNLP 2018
316
+ - OmniSQL / SynSQL-2.5M: Li et al., [arXiv 2503.02240](https://arxiv.org/abs/2503.02240)
317
+ - SLM-SQL: [arXiv 2507.22478](https://arxiv.org/abs/2507.22478)
code/README.md ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SQLant-1B: BIRD submission (Track 1, single GPU)
2
+
3
+ SQLant-1B is a 1.5B text-to-SQL system: **one** base model, [`Qwen/Qwen2.5-Coder-1.5B-Instruct`](https://huggingface.co/Qwen/Qwen2.5-Coder-1.5B-Instruct), with two LoRA adapters (about 18M parameters each) that are switched at runtime:
4
+
5
+ - **generator**: writes SQL;
6
+ - **verifier**: answers "yes" or "no" to "is this candidate SQL correct?", given the question, schema and the candidate's first result rows.
7
+
8
+ Total weights in memory: 1.54B (base) + 2 × 18M (adapters).
9
+
10
+ **BIRD dev (full, 1,534 questions): 55.7 EX.**
11
+
12
+ ## Resources
13
+
14
+ | | |
15
+ |---|---|
16
+ | GPU | 1 × A100 80 GB. Any GPU with 8 GB or more works; peak memory is about 5 GB. |
17
+ | Time | About 10–15 s per question on an Apple M5 Pro (MLX). Expected to be faster on an A100. 1,789 test questions ≈ 4–7 h. |
18
+ | Disk | 3.1 GB base model + 140 MB adapters |
19
+ | Network | Only to download the base model from Hugging Face on first run. Inference makes **no** network calls and sends no data anywhere. |
20
+ | `column_meaning.json` | **Not used.** |
21
+ | Gold SQL | Not used. Only `question`, `evidence` and `db_id` are read from the input file. |
22
+
23
+ ## Setup
24
+
25
+ ```bash
26
+ python -m venv venv && source venv/bin/activate
27
+ pip install -r requirements.txt
28
+ ```
29
+
30
+ The adapters are in `adapters/generator` and `adapters/verifier` (PEFT format) in the submission zip, or in `../generator` and `../verifier` in the Hugging Face repository; `run.py` finds either automatically. The base model downloads automatically from Hugging Face. Alternatively, pass a local copy with `--base /path/to/Qwen2.5-Coder-1.5B-Instruct`.
31
+
32
+ ## Run
33
+
34
+ ```bash
35
+ python run.py --data test.json --db_root test_databases --out predict_test.json
36
+ ```
37
+
38
+ - **Output:** `predict_test.json` maps each question's index in `test.json` to `"<SQL>\t----- bird -----\t<db_id>"`.
39
+ - **Log:** `predict_test.log`.
40
+ - **Resume:** progress is appended to `predict_test.json.progress.jsonl` after every question. If the run stops for any reason, re-run the **same command**: finished questions are skipped and it continues from the first unfinished one.
41
+ - **Errors:** if one question raises an exception, the traceback is logged, `SELECT 1` is written for it, and the run continues. The final log line reports how many questions failed.
42
+ - **Cache:** a per-database value index is built on first use, under `.sqlant_cache/` next to the output file, or `$SQLANT_CACHE` if set.
43
+
44
+ To reproduce our dev result:
45
+
46
+ ```bash
47
+ python run.py --data dev.json --db_root dev_databases --out predict_dev.json
48
+ python compare.py --data dev.json --db_root dev_databases predict_dev.json.progress.jsonl
49
+ ```
50
+
51
+ ## Method (per question)
52
+
53
+ 1. **Draft:** the generator writes a greedy SQL from the full schema (`CREATE TABLE` statements + 3 example rows per table), the hint and the question.
54
+ 2. **Schema pruning:** keeps tables matched by name, by database values mentioned in the question or hint, by the draft SQL, plus foreign-key bridges. Falls back to the full schema when unsure.
55
+ 3. **Candidates:** 1 greedy + 7 sampled (temperature 0.8, top-p 0.95) SQL queries from the pruned prompt.
56
+ 4. **Repair and value snapping** (no model): fixes `T1.col` pointing to a table that lacks `col`, and replaces literals that don't occur in their column with the stored spelling (for example `'Non-essential'` → `'Non-Essential'`).
57
+ 5. **Execute** each candidate (read-only, 15 s timeout) and group candidates by result.
58
+ 6. **Verify:** if there are two or more groups, the verifier scores one SQL per group, `v = logit(yes) − logit(no)`.
59
+ 7. **Pick** the group with the highest `v + 1.5·log(votes)`. If that group returns no rows and another returns rows, the best such group is taken instead.
60
+
61
+ ## Files
62
+
63
+ ```
64
+ run.py entry point (logging, resume, BIRD output format)
65
+ compare.py accuracy / parity check on dev
66
+ convert_adapters.py MLX -> PEFT adapter conversion (already applied)
67
+ sqlant/pipeline.py prompts, execution, grouping, selection
68
+ sqlant/schema_tools.py schema pruning, value index, SQL repair, value snapping
69
+ sqlant/schema_format.py prompt schema format
70
+ sqlant/backend_torch.py PyTorch backend (base + 2 PEFT adapters)
71
+ sqlant/backend_mlx.py MLX backend (Apple Silicon, reference implementation)
72
+ adapters/generator, adapters/verifier PEFT LoRA adapters
73
+ ```
code/compare.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Parity / accuracy check between two runs of run.py on BIRD dev (e.g. --backend mlx vs --backend torch).
2
+
3
+ python compare.py --data dev.json --db_root dev_databases RUN_A.progress.jsonl RUN_B.progress.jsonl
4
+
5
+ Prints, per run, execution accuracy against the gold SQL (set comparison of result rows), and between runs the share
6
+ of identical greedy drafts / greedy candidates and the paired gained/lost counts.
7
+ """
8
+ import argparse
9
+ import json
10
+ import sqlite3
11
+ from math import comb
12
+ from pathlib import Path
13
+
14
+
15
+ def rows(db, sql):
16
+ try:
17
+ con = sqlite3.connect(f"file:{db}?mode=ro", uri=True)
18
+ con.text_factory = lambda b: b.decode(errors="replace")
19
+ r = set(con.execute(sql).fetchall())
20
+ con.close()
21
+ return r
22
+ except Exception: # noqa: BLE001
23
+ return None
24
+
25
+
26
+ def main():
27
+ ap = argparse.ArgumentParser()
28
+ ap.add_argument("--data", required=True)
29
+ ap.add_argument("--db_root", required=True)
30
+ ap.add_argument("runs", nargs="+")
31
+ a = ap.parse_args()
32
+ data = json.loads(Path(a.data).read_text())
33
+ runs = [{r["idx"]: r for r in (json.loads(l) for l in Path(f).read_text().splitlines() if l.strip())} for f in a.runs]
34
+ ids = sorted(set.intersection(*[set(r) for r in runs]))
35
+ gold = {}
36
+ correct = [{} for _ in runs]
37
+ for i in ids:
38
+ ex = data[i]
39
+ db = str(Path(a.db_root) / ex["db_id"] / f"{ex['db_id']}.sqlite")
40
+ gold[i] = rows(db, ex["SQL"])
41
+ for k, run in enumerate(runs):
42
+ p = rows(db, run[i]["sql"])
43
+ correct[k][i] = p is not None and p == gold[i]
44
+ for k, f in enumerate(a.runs):
45
+ print(f"{f}: EX {100 * sum(correct[k].values()) / len(ids):.1f} on {len(ids)} questions")
46
+ if len(runs) == 2:
47
+ A, B = runs
48
+ same_d = sum(A[i].get("draft", "").strip() == B[i].get("draft", "").strip() for i in ids)
49
+ same_g = sum((A[i].get("candidates") or [""])[0].strip() == (B[i].get("candidates") or [""])[0].strip() for i in ids)
50
+ w = sum(correct[1][i] and not correct[0][i] for i in ids)
51
+ l = sum(correct[0][i] and not correct[1][i] for i in ids)
52
+ n = w + l
53
+ p = min(1.0, 2 * sum(comb(n, j) for j in range(min(w, l) + 1)) / 2 ** n) if n else 1.0
54
+ print(f"identical greedy drafts {same_d}/{len(ids)}, identical greedy candidates {same_g}/{len(ids)}")
55
+ print(f"run B vs run A: +{w} / -{l} (McNemar p = {p:.3f})")
56
+
57
+
58
+ if __name__ == "__main__":
59
+ main()
code/convert_adapters.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Convert SQLant's MLX LoRA adapters to PEFT format (exact, no retraining).
2
+
3
+ MLX LoRALinear: y = W x + scale * (x @ lora_a) @ lora_b lora_a: (in, r), lora_b: (r, out)
4
+ PEFT LoRA: y = W x + (alpha / r) * B(A(x)) A.weight: (r, in), B.weight: (out, r)
5
+ => A = lora_a.T, B = lora_b.T, alpha = scale * r.
6
+
7
+ python convert_adapters.py <mlx_adapter_dir> <peft_out_dir>
8
+ """
9
+ import json
10
+ import re
11
+ import sys
12
+ from pathlib import Path
13
+
14
+ import numpy as np
15
+ from safetensors.numpy import load_file, save_file
16
+
17
+ BASE = "Qwen/Qwen2.5-Coder-1.5B-Instruct"
18
+
19
+
20
+ def convert(src, dst):
21
+ src, dst = Path(src), Path(dst)
22
+ cfg = json.loads((src / "adapter_config.json").read_text())
23
+ lp = cfg["lora_parameters"]
24
+ w = load_file(str(src / "adapters.safetensors"))
25
+ out, layers, modules = {}, set(), set()
26
+ for k, v in w.items():
27
+ m = re.fullmatch(r"model\.layers\.(\d+)\.(self_attn|mlp)\.(\w+)\.lora_([ab])", k)
28
+ assert m, f"unexpected key {k}"
29
+ layer, block, mod, ab = m.groups()
30
+ layers.add(int(layer))
31
+ modules.add(mod)
32
+ name = f"base_model.model.model.layers.{layer}.{block}.{mod}.lora_{ab.upper()}.weight"
33
+ out[name] = np.ascontiguousarray(v.T.astype(np.float32))
34
+ dst.mkdir(parents=True, exist_ok=True)
35
+ save_file(out, str(dst / "adapter_model.safetensors"))
36
+ peft_cfg = {
37
+ "peft_type": "LORA", "task_type": "CAUSAL_LM", "base_model_name_or_path": cfg.get("base_model", BASE),
38
+ "r": lp["rank"], "lora_alpha": lp["scale"] * lp["rank"], "lora_dropout": 0.0, "bias": "none",
39
+ "target_modules": sorted(modules), "layers_to_transform": sorted(layers), "fan_in_fan_out": False,
40
+ "inference_mode": True, "use_rslora": False, "use_dora": False, "init_lora_weights": True,
41
+ "modules_to_save": None,
42
+ }
43
+ (dst / "adapter_config.json").write_text(json.dumps(peft_cfg, indent=2))
44
+ print(f"{src} -> {dst}: {len(out)} tensors, layers {min(layers)}-{max(layers)}, modules {sorted(modules)}")
45
+
46
+
47
+ if __name__ == "__main__":
48
+ convert(sys.argv[1], sys.argv[2])
code/requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ torch>=2.4
2
+ transformers>=4.45
3
+ peft>=0.13
4
+ accelerate>=0.34
5
+ safetensors>=0.4
6
+ numpy>=1.26
7
+ sqlglot==30.31.0
code/run.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SQLant-1B: BIRD-format inference with logging and resume.
2
+
3
+ python run.py --data test.json --db_root test_databases --out predict_test.json \
4
+ [--base Qwen/Qwen2.5-Coder-1.5B-Instruct] [--generator adapters/generator] [--verifier adapters/verifier] \
5
+ [--backend torch|mlx] [--limit N]
6
+
7
+ Progress is appended to <out>.progress.jsonl after every question; re-running the same command skips finished
8
+ questions and continues from the first unfinished one. The final file maps the question's index in --data to
9
+ "SQL\t----- bird -----\t<db_id>" (BIRD's prediction format).
10
+ """
11
+ import argparse
12
+ import json
13
+ import logging
14
+ import os
15
+ import sys
16
+ import time
17
+ import traceback
18
+ from pathlib import Path
19
+
20
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
21
+
22
+
23
+ def main():
24
+ ap = argparse.ArgumentParser()
25
+ ap.add_argument("--data", required=True)
26
+ ap.add_argument("--db_root", required=True)
27
+ ap.add_argument("--out", required=True)
28
+ ap.add_argument("--base", default="Qwen/Qwen2.5-Coder-1.5B-Instruct")
29
+ here = Path(__file__).resolve().parent
30
+
31
+ def default_adapter(name): # submission zip: ./adapters/<name>; Hugging Face repo: ../<name> next to code/
32
+ for p in (here / "adapters" / name, here.parent / name):
33
+ if (p / "adapter_config.json").exists():
34
+ return str(p)
35
+ return str(here / "adapters" / name)
36
+ ap.add_argument("--generator", default=default_adapter("generator"))
37
+ ap.add_argument("--verifier", default=default_adapter("verifier"))
38
+ ap.add_argument("--backend", default="torch", choices=["torch", "mlx"])
39
+ ap.add_argument("--limit", type=int, default=None)
40
+ ap.add_argument("--seed", type=int, default=0)
41
+ a = ap.parse_args()
42
+
43
+ out = Path(a.out)
44
+ prog = out.with_suffix(out.suffix + ".progress.jsonl")
45
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s",
46
+ handlers=[logging.StreamHandler(), logging.FileHandler(out.with_suffix(".log"))])
47
+ os.environ.setdefault("SQLANT_CACHE", str(out.parent / ".sqlant_cache"))
48
+ from sqlant import pipeline # imported after SQLANT_CACHE is set: schema_tools reads it at import time
49
+
50
+ data = json.loads(Path(a.data).read_text())
51
+ if a.limit:
52
+ data = data[:a.limit]
53
+ done = {}
54
+ if prog.exists():
55
+ for line in prog.read_text().splitlines():
56
+ if line.strip():
57
+ r = json.loads(line)
58
+ done[r["idx"]] = r
59
+ logging.info("%d questions, %d already done (resuming)", len(data), len(done))
60
+
61
+ if a.backend == "torch":
62
+ from sqlant.backend_torch import TorchBackend
63
+ be = TorchBackend(a.base, a.generator, a.verifier, seed=a.seed)
64
+ else:
65
+ from sqlant.backend_mlx import MLXBackend
66
+ be = MLXBackend(a.base, a.generator, a.verifier, seed=a.seed)
67
+
68
+ t0 = time.time()
69
+ n_new = 0
70
+ with prog.open("a") as f:
71
+ for i, ex in enumerate(data):
72
+ if i in done:
73
+ continue
74
+ db = str(Path(a.db_root) / ex["db_id"] / f"{ex['db_id']}.sqlite")
75
+ try:
76
+ r = pipeline.answer(be, db, ex["question"], ex.get("evidence") or "")
77
+ rec = {"idx": i, "db_id": ex["db_id"], "sql": r["sql"], "groups": r["groups"], "draft": r["draft"], "candidates": r["candidates"]}
78
+ except Exception: # noqa: BLE001 - log and fall back so one bad question can't stop the run
79
+ logging.error("question %d failed:\n%s", i, traceback.format_exc())
80
+ rec = {"idx": i, "db_id": ex["db_id"], "sql": "SELECT 1", "error": True}
81
+ f.write(json.dumps(rec) + "\n")
82
+ f.flush()
83
+ done[i] = rec
84
+ n_new += 1
85
+ n = len(done)
86
+ if n % 10 == 0 or n == len(data):
87
+ rate = (time.time() - t0) / n_new
88
+ logging.info("%d/%d done (%.1f s/question this session)", n, len(data), rate)
89
+
90
+ preds = {str(i): f"{done[i]['sql']}\t----- bird -----\t{done[i]['db_id']}" for i in sorted(done)}
91
+ out.write_text(json.dumps(preds, indent=2))
92
+ n_err = sum(1 for r in done.values() if r.get("error"))
93
+ logging.info("wrote %s (%d predictions, %d failed questions)", out, len(preds), n_err)
94
+
95
+
96
+ if __name__ == "__main__":
97
+ main()
code/sqlant/__init__.py ADDED
File without changes
code/sqlant/backend_mlx.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """MLX backend (Apple Silicon): the evaluated reference implementation, used for parity checks."""
2
+ from .pipeline import MAX_TOKENS, TOP_P
3
+
4
+
5
+ class MLXBackend:
6
+ def __init__(self, base, generator, verifier, seed=0):
7
+ import mlx.core as mx
8
+ from mlx_lm import load
9
+ self.mx = mx
10
+ self.gen_model, self.tok = load(base, adapter_path=generator)
11
+ self.ver_model, self.vtok = load(base, adapter_path=verifier)
12
+ self.yes, self.no = self.vtok.encode("yes")[0], self.vtok.encode("no")[0]
13
+ mx.random.seed(seed)
14
+
15
+ def generate(self, messages, n, temp):
16
+ from mlx_lm import batch_generate
17
+ from mlx_lm.sample_utils import make_sampler
18
+ ids = self.tok.apply_chat_template(messages, add_generation_prompt=True)
19
+ sampler = make_sampler(temp=0.0) if temp == 0.0 else make_sampler(temp=temp, top_p=TOP_P)
20
+ out = batch_generate(self.gen_model, self.tok, [ids] * n, max_tokens=MAX_TOKENS, sampler=sampler).texts
21
+ self.mx.clear_cache()
22
+ return out
23
+
24
+ def score(self, user):
25
+ ids = self.vtok.apply_chat_template([{"role": "user", "content": user}], add_generation_prompt=True)
26
+ if isinstance(ids, dict) or hasattr(ids, "keys"):
27
+ ids = ids["input_ids"]
28
+ v = (lambda lg: (lg[self.yes] - lg[self.no]).item())(self.ver_model(self.mx.array([ids]))[0, -1])
29
+ self.mx.clear_cache()
30
+ return v
code/sqlant/backend_torch.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PyTorch backend: one copy of Qwen2.5-Coder-1.5B-Instruct + two PEFT LoRA adapters (generator, verifier),
2
+ switched with set_adapter. Decoding matches the MLX evaluation exactly: no repetition penalty, no top-k
3
+ (the base model's generation_config.json sets top_k=20 and repetition_penalty=1.1, so everything is overridden)."""
4
+ import torch
5
+ from peft import PeftModel
6
+ from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig
7
+
8
+ from .pipeline import MAX_TOKENS, TOP_P
9
+
10
+
11
+ def _free():
12
+ """Release cached allocator blocks. Without this, MPS keeps every differently-shaped KV cache from
13
+ generate() and grew to 18 GB over 150 questions; on CUDA it just bounds fragmentation."""
14
+ if torch.cuda.is_available():
15
+ torch.cuda.empty_cache()
16
+ elif torch.backends.mps.is_available():
17
+ torch.mps.empty_cache()
18
+
19
+
20
+ class TorchBackend:
21
+ def __init__(self, base, generator, verifier, device=None, dtype=torch.bfloat16, seed=0):
22
+ self.device = device or ("cuda" if torch.cuda.is_available() else
23
+ "mps" if torch.backends.mps.is_available() else "cpu")
24
+ self.tok = AutoTokenizer.from_pretrained(base)
25
+ model = AutoModelForCausalLM.from_pretrained(base, torch_dtype=dtype).to(self.device)
26
+ model = PeftModel.from_pretrained(model, generator, adapter_name="generator")
27
+ model.load_adapter(verifier, adapter_name="verifier")
28
+ self.model = model.eval()
29
+ self.yes = self.tok.encode("yes")[0]
30
+ self.no = self.tok.encode("no")[0]
31
+ eos = self.tok.convert_tokens_to_ids(["<|im_end|>", "<|endoftext|>"])
32
+ self.gen_kw = dict(max_new_tokens=MAX_TOKENS, eos_token_id=eos, pad_token_id=self.tok.pad_token_id or eos[-1],
33
+ repetition_penalty=1.0, top_k=0)
34
+ torch.manual_seed(seed)
35
+
36
+ def _ids(self, messages):
37
+ ids = self.tok.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt")
38
+ if not isinstance(ids, torch.Tensor): # newer transformers may return a BatchEncoding
39
+ ids = ids["input_ids"]
40
+ return ids.to(self.device)
41
+
42
+ @torch.inference_mode()
43
+ def generate(self, messages, n, temp):
44
+ self.model.set_adapter("generator")
45
+ ids = self._ids(messages)
46
+ if temp == 0.0:
47
+ cfg = GenerationConfig(do_sample=False, num_return_sequences=n, **self.gen_kw)
48
+ else:
49
+ cfg = GenerationConfig(do_sample=True, temperature=temp, top_p=TOP_P, num_return_sequences=n, **self.gen_kw)
50
+ out = self.model.generate(input_ids=ids, attention_mask=torch.ones_like(ids), generation_config=cfg)
51
+ texts = [self.tok.decode(o[ids.shape[1]:], skip_special_tokens=True) for o in out.cpu()]
52
+ del out, ids
53
+ _free()
54
+ return texts
55
+
56
+ @torch.inference_mode()
57
+ def score(self, user):
58
+ self.model.set_adapter("verifier")
59
+ ids = self._ids([{"role": "user", "content": user}])
60
+ logits = self.model(input_ids=ids).logits[0, -1].float()
61
+ v = (logits[self.yes] - logits[self.no]).item()
62
+ del logits, ids
63
+ _free()
64
+ return v
code/sqlant/pipeline.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SQLant inference pipeline, independent of the model backend (PyTorch or MLX).
2
+
3
+ Per question (identical to the evaluated pipeline in the SQLant repository):
4
+ 1. draft = generator, greedy, full-schema prompt
5
+ 2. prompt = pruned schema (tables linked from question / evidence / matched values / draft SQL)
6
+ 3. cands = generator on the pruned prompt: 1 greedy + 7 samples (T 0.8, top-p 0.95)
7
+ 4. execute each candidate after SQL repair + value snapping (read-only, 15 s timeout)
8
+ 5. group candidates by result rows; if >= 2 groups, the verifier scores one SQL per group
9
+ 6. pick argmax v + 1.5 * log(votes); if the pick returns no rows, the best group that returns rows
10
+ (no executable candidate -> the greedy candidate)
11
+ """
12
+ import hashlib
13
+ import json
14
+ import math
15
+ import re
16
+ import sqlite3
17
+ import time
18
+ from collections import defaultdict
19
+ from pathlib import Path
20
+
21
+ from . import schema_tools as S
22
+ from .schema_format import build_prompt, schema_text
23
+
24
+ SYSTEM = "You are an expert SQLite developer who writes correct, efficient SQL."
25
+ VSYS = "You are an expert SQLite reviewer. Decide whether the candidate SQL correctly answers the question."
26
+ N_SAMPLES, TEMP, TOP_P, MAX_TOKENS = 7, 0.8, 0.95, 512
27
+ ALPHA = 1.5
28
+ QUERY_TIMEOUT_S = 15
29
+
30
+
31
+ # ---------------------------------------------------------------- prompts
32
+ def full_prompt(db, question, evidence):
33
+ return build_prompt(schema_text(Path(db)), question, evidence or None)
34
+
35
+
36
+ def pruned_prompt(db, question, evidence, draft_sql):
37
+ hits = S.match_values(question, evidence or "", db)
38
+ keep = S.link_tables(question, evidence or "", db, hits, draft_sql)
39
+ return build_prompt(S.schema_text_subset(db, keep), question, evidence or None)
40
+
41
+
42
+ def chat_messages(user):
43
+ return [{"role": "user", "content": f"{SYSTEM}\n\n{user}"}]
44
+
45
+
46
+ def extract_sql(text):
47
+ text = re.sub(r"<think>.*?</think>", "", text, flags=re.S)
48
+ blocks = re.findall(r"```(?:sql|sqlite)?\s*\n?(.*?)```", text, flags=re.S | re.I)
49
+ if blocks:
50
+ sql = blocks[-1]
51
+ else:
52
+ m = re.search(r"\b(WITH|SELECT)\b.*", text, flags=re.S | re.I)
53
+ sql = m.group(0) if m else text
54
+ sql = sql.strip()
55
+ sql = re.sub(r"\A(?:[ \t]*--[^\n]*\n)+", "", sql + "\n").strip()
56
+ if ";" in sql:
57
+ sql = sql.split(";")[0]
58
+ return sql.strip()
59
+
60
+
61
+ # ---------------------------------------------------------------- execution
62
+ def run_sql(db, sql, timeout=QUERY_TIMEOUT_S):
63
+ con = sqlite3.connect(f"file:{db}?mode=ro", uri=True)
64
+ con.text_factory = lambda b: b.decode(errors="replace")
65
+ deadline = time.monotonic() + timeout
66
+ con.set_progress_handler(lambda: 1 if time.monotonic() > deadline else 0, 10_000)
67
+ try:
68
+ return set(con.execute(sql).fetchall()), None
69
+ except Exception as e: # noqa: BLE001
70
+ return None, f"{type(e).__name__}: {e}"[:200]
71
+ finally:
72
+ con.close()
73
+
74
+
75
+ def _norm(rows):
76
+ return set(map(tuple, json.loads(json.dumps([list(t) for t in rows], default=str))))
77
+
78
+
79
+ def execute(db, sql):
80
+ """repair + value snapping + run -> None (error) or {key, fixed, n_rows, preview}."""
81
+ fixed = S.repair_sql(sql, db) or sql
82
+ fixed = S.snap_values(fixed, db) or fixed
83
+ rows, _ = run_sql(db, fixed)
84
+ if rows is None:
85
+ return None
86
+ rows = sorted(_norm(rows), key=repr)
87
+ return {"key": hashlib.sha1(repr(sorted(map(repr, rows))).encode()).hexdigest(),
88
+ "fixed": fixed, "n_rows": len(rows), "preview": [list(r) for r in rows[:5]]}
89
+
90
+
91
+ # ---------------------------------------------------------------- verifier input
92
+ def fmt_result(r):
93
+ def cell(c):
94
+ s = "NULL" if c is None else str(c)
95
+ return s if len(s) <= 60 else s[:57] + "..."
96
+ if r["n_rows"] == 0:
97
+ return "(no rows)"
98
+ lines = [" | ".join(cell(c) for c in row) for row in r["preview"]]
99
+ more = f"\n... ({r['n_rows']} rows in total)" if r["n_rows"] > len(r["preview"]) else f"\n({r['n_rows']} rows)"
100
+ return "\n".join(lines) + more
101
+
102
+
103
+ def verifier_message(prompt, sql, res):
104
+ prompt = prompt.split("\n\nWrite one SQLite query", 1)[0]
105
+ return (f"{VSYS}\n\n{prompt}\n\nCandidate SQL:\n```sql\n{sql}\n```\n\n"
106
+ f"Execution result (first rows):\n{fmt_result(res)}\n\nIs the candidate SQL correct? Answer yes or no.")
107
+
108
+
109
+ # ---------------------------------------------------------------- selection
110
+ def select(prompt, cands, results, score_fn):
111
+ """cands[0] is the greedy candidate. results[i] = execute(...) or None. Returns (final_sql, info)."""
112
+ g = defaultdict(list)
113
+ for j, r in enumerate(results):
114
+ if r is not None:
115
+ g[r["key"]].append(j)
116
+ if not g:
117
+ return (results[0]["fixed"] if results[0] else cands[0]), {"groups": 0}
118
+ groups = []
119
+ for key, idx in g.items():
120
+ res = results[idx[0]]
121
+ v = score_fn(verifier_message(prompt, res["fixed"].strip(), res)) if len(g) > 1 else 0.0
122
+ groups.append({"key": key, "votes": len(idx), "first": idx[0], "v": v, "n_rows": res["n_rows"]})
123
+ s = lambda x: x["v"] + ALPHA * math.log(x["votes"]) # noqa: E731
124
+ best = max(groups, key=s)
125
+ if best["n_rows"] == 0: # empty-result rule
126
+ ok = [x for x in groups if x["n_rows"] > 0 and not _zero_null(results[x["first"]])]
127
+ best = max(ok, key=s) if ok else best
128
+ return results[best["first"]]["fixed"].strip(), {"groups": len(groups), "picked": best}
129
+
130
+
131
+ def _zero_null(r): # flag_rule.flag == "zero/null" -> not "ok", so not a fallback target
132
+ p = r["preview"]
133
+ return r["n_rows"] == 1 and len(p[0]) == 1 and p[0][0] in (0, None)
134
+
135
+
136
+ def answer(backend, db, question, evidence):
137
+ """Full pipeline for one question. backend: generate(messages, n, temp) -> [texts]; score(user) -> float."""
138
+ draft = extract_sql(backend.generate(chat_messages(full_prompt(db, question, evidence)), 1, 0.0)[0])
139
+ prompt = pruned_prompt(db, question, evidence, draft)
140
+ msgs = chat_messages(prompt)
141
+ texts = backend.generate(msgs, 1, 0.0) + backend.generate(msgs, N_SAMPLES, TEMP)
142
+ cands = [extract_sql(t) for t in texts]
143
+ results = [execute(db, c) for c in cands]
144
+ final, info = select(prompt, cands, results, backend.score)
145
+ return {"sql": final, "draft": draft, "candidates": cands, "groups": info.get("groups", 0)}
code/sqlant/schema_format.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Prompt schema format (copied from the SQLant repository, scripts/build_eval_set.py)."""
2
+ import sqlite3
3
+ from pathlib import Path
4
+
5
+ N_EXAMPLE_ROWS = 3
6
+ MAX_VAL_CHARS = 40
7
+
8
+
9
+ def _fmt(v):
10
+ s = repr(v) if isinstance(v, str) else str(v)
11
+ return s if len(s) <= MAX_VAL_CHARS else s[:MAX_VAL_CHARS] + "...'"
12
+
13
+
14
+ def schema_text(db_path: Path) -> str:
15
+ con = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)
16
+ con.text_factory = lambda b: b.decode(errors="replace")
17
+ cur = con.cursor()
18
+ parts = []
19
+ tables = cur.execute(
20
+ "SELECT name, sql FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'"
21
+ ).fetchall()
22
+ for name, ddl in tables:
23
+ block = ddl.strip() + ";"
24
+ try:
25
+ rows = cur.execute(f'SELECT * FROM "{name}" LIMIT {N_EXAMPLE_ROWS}').fetchall()
26
+ cols = [d[0] for d in cur.description]
27
+ if rows:
28
+ lines = [" | ".join(cols)] + [" | ".join(_fmt(v) for v in r) for r in rows]
29
+ block += f"\n/* {len(rows)} example rows from {name}:\n" + "\n".join(lines) + "\n*/"
30
+ except sqlite3.Error:
31
+ pass
32
+ parts.append(block)
33
+ con.close()
34
+ return "\n\n".join(parts)
35
+
36
+
37
+ def build_prompt(schema: str, question: str, evidence: str | None) -> str:
38
+ p = f"Database schema (SQLite):\n{schema}\n\n"
39
+ if evidence:
40
+ p += f"External knowledge: {evidence}\n\n"
41
+ p += (
42
+ f"Question: {question}\n\n"
43
+ "Write one SQLite query that answers the question. "
44
+ "Return only the SQL inside a ```sql code block, with no explanation."
45
+ )
46
+ return p
code/sqlant/schema_tools.py ADDED
@@ -0,0 +1,449 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Copied unchanged from the SQLant repository (scripts/schema_tools.py) except for paths."""
2
+ """Inference-time helpers for SQLant: schema pruning, value retrieval, alias repair.
3
+
4
+ - db_meta(db) tables -> columns, foreign keys (cached)
5
+ - value_index(db) lowercase text value -> [(table, column, original)] (cached on disk)
6
+ - match_values(q, ev, db) database values literally mentioned in the question / evidence
7
+ - link_tables(...) tables to keep: lexical match on names + value matches + draft SQL tables
8
+ + FK bridges; falls back to the full schema when unsure
9
+ - schema_text_subset(...) same format as build_eval_set.schema_text, restricted to some tables
10
+ - values_block(matches) prompt block listing matched values
11
+ - alias_repair(sql, db) re-point `T1.col` to the one joined table that actually has `col`
12
+ """
13
+ import json
14
+ import os
15
+ import pickle
16
+ import re
17
+ import sqlite3
18
+ import sys
19
+ from functools import lru_cache
20
+ from pathlib import Path
21
+
22
+ import sqlglot
23
+ from sqlglot import exp
24
+
25
+ ROOT = Path.cwd() # database paths may be absolute (ROOT / absolute == absolute) or relative to the working dir
26
+ from .schema_format import N_EXAMPLE_ROWS, _fmt # noqa: E402
27
+
28
+ VALUE_DIR = Path(os.environ.get("SQLANT_CACHE", ".sqlant_cache")) / "value_index"
29
+ MAX_VALUE_LEN = 60
30
+ MAX_DISTINCT_PER_COL = 20_000
31
+ STOP = set("""a an the of in on at to for from by with and or not is are was were be been what which who whom whose
32
+ how many much list give show find name names number count all each per than that this these those their there
33
+ does do did have has had please average total among between more most less least only any its it as into
34
+ """.split())
35
+
36
+
37
+ def _con(db):
38
+ con = sqlite3.connect(f"file:{ROOT / db}?mode=ro", uri=True)
39
+ con.text_factory = lambda b: b.decode(errors="replace")
40
+ return con
41
+
42
+
43
+ @lru_cache(maxsize=256)
44
+ def db_meta(db: str) -> dict:
45
+ con = _con(db)
46
+ tables = {}
47
+ fks = []
48
+ for (name,) in con.execute("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'"):
49
+ cols = [(r[1], (r[2] or "").upper()) for r in con.execute(f'PRAGMA table_info("{name}")')]
50
+ tables[name] = cols
51
+ for r in con.execute(f'PRAGMA foreign_key_list("{name}")'):
52
+ fks.append((name, r[2])) # (from_table, to_table)
53
+ # FK column pairs (from_table, from_col, to_table, to_col); to_col None -> primary key of to_table
54
+ pks = {}
55
+ for name in tables:
56
+ pk = [r[1] for r in con.execute(f'PRAGMA table_info("{name}")') if r[5]]
57
+ pks[name] = pk[0] if len(pk) == 1 else None
58
+ lower = {t.lower(): t for t in tables}
59
+ fkcols = []
60
+ for name in tables:
61
+ for r in con.execute(f'PRAGMA foreign_key_list("{name}")'):
62
+ to_t = lower.get((r[2] or "").lower())
63
+ if to_t:
64
+ fkcols.append((name, r[3], to_t, r[4] or pks.get(to_t)))
65
+ con.close()
66
+ return {"tables": tables, "fks": fks, "fkcols": [f for f in fkcols if f[3]], "pks": pks}
67
+
68
+
69
+ def join_keys(db: str, a: str, b: str):
70
+ """(col_in_a, col_in_b) to join tables a and b: declared FK first, then `<b>_id`-style naming."""
71
+ meta = db_meta(db)
72
+ for ft, fc, tt, tc in meta["fkcols"]:
73
+ if ft.lower() == a.lower() and tt.lower() == b.lower():
74
+ return fc, tc
75
+ if ft.lower() == b.lower() and tt.lower() == a.lower():
76
+ return tc, fc
77
+ cols = {t.lower(): {c.lower(): c for c, _ in cs} for t, cs in meta["tables"].items()}
78
+ ca, cb = cols.get(a.lower(), {}), cols.get(b.lower(), {})
79
+ pkb, pka = meta["pks"].get(b), meta["pks"].get(a)
80
+ for name in (f"{b.lower()}_id", f"{b.lower()}id"):
81
+ if name in ca and pkb:
82
+ return ca[name], pkb
83
+ for name in (f"{a.lower()}_id", f"{a.lower()}id"):
84
+ if name in cb and pka:
85
+ return pka, cb[name]
86
+ return None
87
+
88
+
89
+ def _words(s: str) -> list:
90
+ return re.findall(r"[a-z0-9]+", (s or "").lower())
91
+
92
+
93
+ def _name_tokens(name: str) -> set:
94
+ s = re.sub(r"([a-z])([A-Z])", r"\1 \2", name)
95
+ return {w for w in _words(s) if w not in STOP and len(w) > 1}
96
+
97
+
98
+ def _stem(w):
99
+ for suf in ("ies", "es", "s"):
100
+ if w.endswith(suf) and len(w) - len(suf) >= 3:
101
+ return w[: -len(suf)] + ("y" if suf == "ies" else "")
102
+ return w
103
+
104
+
105
+ # ------------------------------------------------------------------ values
106
+ def value_index(db: str) -> dict:
107
+ VALUE_DIR.mkdir(parents=True, exist_ok=True)
108
+ f = VALUE_DIR / (re.sub(r"[^A-Za-z0-9_]+", "_", db) + ".pkl")
109
+ if f.exists():
110
+ return pickle.loads(f.read_bytes())
111
+ idx: dict = {}
112
+ con = _con(db)
113
+ for t, cols in db_meta(db)["tables"].items():
114
+ for c, typ in cols:
115
+ if typ and not any(k in typ for k in ("CHAR", "TEXT", "CLOB", "VARCHAR")) and typ != "":
116
+ continue
117
+ try:
118
+ rows = con.execute(
119
+ f'SELECT DISTINCT "{c}" FROM "{t}" WHERE typeof("{c}")=\'text\' '
120
+ f'AND length("{c}") BETWEEN 2 AND {MAX_VALUE_LEN} LIMIT {MAX_DISTINCT_PER_COL}').fetchall()
121
+ except sqlite3.Error:
122
+ continue
123
+ for (v,) in rows:
124
+ k = v.strip().lower()
125
+ if k and not k.isdigit():
126
+ idx.setdefault(k, []).append((t, c, v))
127
+ con.close()
128
+ tmp = f.with_suffix(f".{os.getpid()}.tmp") # atomic: parallel workers may build the same DB
129
+ tmp.write_bytes(pickle.dumps(idx))
130
+ os.replace(tmp, f)
131
+ return idx
132
+
133
+
134
+ def match_values(question: str, evidence: str, db: str, max_hits: int = 12) -> list:
135
+ """Values whose full text appears in the question/evidence (n-grams up to 6 words, case-insensitive)."""
136
+ idx = value_index(db)
137
+ text = f"{question} {evidence or ''}"
138
+ cands = {m.strip().lower() for m in re.findall(r"'([^']{2,60})'|\"([^\"]{2,60})\"", text) for m in m if m}
139
+ toks = re.findall(r"[A-Za-z0-9][A-Za-z0-9&.'\-]*", text)
140
+ for n in range(6, 0, -1):
141
+ for i in range(len(toks) - n + 1):
142
+ g = " ".join(toks[i:i + n]).strip(".").lower()
143
+ if n == 1 and (g in STOP or len(g) < 3 or g.isdigit()):
144
+ continue
145
+ cands.add(g)
146
+ hits, seen = [], set()
147
+ for g in sorted(cands, key=len, reverse=True):
148
+ for t, c, v in idx.get(g, [])[:4]:
149
+ if (t, c, v) not in seen:
150
+ seen.add((t, c, v))
151
+ hits.append((t, c, v))
152
+ # prefer longer (more specific) values; cap
153
+ hits.sort(key=lambda h: -len(h[2]))
154
+ return hits[:max_hits]
155
+
156
+
157
+ def strict_values(hits: list, question: str, evidence: str, db: str, per_value: int = 2) -> list:
158
+ """Filter match_values hits down to the ones that are likely meant as values (fewer misleading lines).
159
+
160
+ 1. fragments: drop a value that is a word-span inside another matched value ('Sussex' < 'West Sussex')
161
+ 2. schema words: drop single-word values that are also a table/column name word ('platform' table vs
162
+ genre 'Platform') -- in the question the word names the schema element, not a stored value
163
+ 3. case variants: per column keep one spelling (the one written in the question, else the first)
164
+ 4. same value in many columns: prefer columns whose table/column words appear in the question; at most
165
+ `per_value` columns per value
166
+ """
167
+ text = f"{question} {evidence or ''}"
168
+ low = {h[2].strip().lower() for h in hits}
169
+ meta = db_meta(db)
170
+ schema_words = {_stem(w) for t, cols in meta["tables"].items()
171
+ for name in [t] + [c for c, _ in cols] for w in _name_tokens(name)}
172
+ q_words = {_stem(w) for w in _words(text) if w not in STOP and len(w) > 1}
173
+
174
+ def fragment(v):
175
+ v = v.lower()
176
+ return any(v != o and re.search(rf"(^|\W){re.escape(v)}($|\W)", o) for o in low)
177
+
178
+ kept = [h for h in hits if not fragment(h[2])
179
+ and not (len(_words(h[2])) == 1 and _stem(h[2].strip().lower()) in schema_words)]
180
+ by_col = {}
181
+ for t, c, v in kept: # 3. one spelling per column
182
+ k = (t, c, v.lower())
183
+ if k not in by_col or (v in text and by_col[k] not in text):
184
+ by_col[k] = v
185
+ by_val = {}
186
+ for (t, c, vl), v in by_col.items():
187
+ by_val.setdefault(vl, []).append((t, c, v))
188
+ out = []
189
+ for vl, cands in by_val.items(): # 4. rank columns by overlap with the question
190
+ def rel(h):
191
+ return len(q_words & {_stem(w) for w in _name_tokens(h[0]) | _name_tokens(h[1])})
192
+ cands.sort(key=rel, reverse=True)
193
+ best = rel(cands[0])
194
+ out.extend([h for h in cands if rel(h) == best][:per_value] if best else cands[:per_value])
195
+ out.sort(key=lambda h: -len(h[2]))
196
+ return out
197
+
198
+
199
+ def values_block(hits: list) -> str:
200
+ if not hits:
201
+ return ""
202
+ lines = [f"{t}.{c} = {v!r}" for t, c, v in hits]
203
+ return "\n\n/* Values in the database that match words in the question:\n" + "\n".join(lines) + "\n*/"
204
+
205
+
206
+ # ------------------------------------------------------------------ pruning
207
+ def sql_tables(sql: str, db: str) -> set:
208
+ names = {t.lower(): t for t in db_meta(db)["tables"]}
209
+ try:
210
+ tree = sqlglot.parse_one(sql, read="sqlite")
211
+ return {names[t.name.lower()] for t in tree.find_all(exp.Table) if t.name.lower() in names}
212
+ except Exception: # noqa: BLE001
213
+ return {names[w] for w in _words(sql) if w in names}
214
+
215
+
216
+ def link_tables(question: str, evidence: str, db: str, value_hits=(), draft_sql: str | None = None,
217
+ min_tables_to_prune: int = 5) -> list:
218
+ meta = db_meta(db)
219
+ tables = list(meta["tables"])
220
+ if len(tables) < min_tables_to_prune:
221
+ return tables
222
+ q = {_stem(w) for w in _words(f"{question} {evidence or ''}") if w not in STOP and len(w) > 1}
223
+ keep = set()
224
+ for t, cols in meta["tables"].items():
225
+ if {_stem(w) for w in _name_tokens(t)} & q:
226
+ keep.add(t)
227
+ for c, _ in cols:
228
+ ct = {_stem(w) for w in _name_tokens(c)}
229
+ if ct and (ct <= q or (len(ct) >= 2 and len(ct & q) >= 2)):
230
+ keep.add(t)
231
+ keep |= {t for t, _, _ in value_hits}
232
+ if draft_sql:
233
+ keep |= sql_tables(draft_sql, db)
234
+ if not keep:
235
+ return tables
236
+ # FK bridges: add any table that links two kept tables
237
+ for a in tables:
238
+ if a in keep:
239
+ continue
240
+ nbrs = {y for x, y in meta["fks"] if x == a} | {x for x, y in meta["fks"] if y == a}
241
+ if len(nbrs & keep) >= 2:
242
+ keep.add(a)
243
+ return [t for t in tables if t in keep]
244
+
245
+
246
+ def schema_text_subset(db: str, keep: list) -> str:
247
+ con = _con(db)
248
+ parts = []
249
+ ddls = dict(con.execute("SELECT name, sql FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'"))
250
+ for name in keep:
251
+ block = ddls[name].strip() + ";"
252
+ try:
253
+ cur = con.execute(f'SELECT * FROM "{name}" LIMIT {N_EXAMPLE_ROWS}')
254
+ rows = cur.fetchall()
255
+ cols = [d[0] for d in cur.description]
256
+ if rows:
257
+ lines = [" | ".join(cols)] + [" | ".join(_fmt(v) for v in r) for r in rows]
258
+ block += f"\n/* {len(rows)} example rows from {name}:\n" + "\n".join(lines) + "\n*/"
259
+ except sqlite3.Error:
260
+ pass
261
+ parts.append(block)
262
+ con.close()
263
+ return "\n\n".join(parts)
264
+
265
+
266
+ def relations_block(db: str, keep: list) -> str:
267
+ """Declared foreign keys between the shown tables, one join condition per line (empty if none)."""
268
+ meta = db_meta(db)
269
+ shown = {t.lower() for t in keep}
270
+ lines = []
271
+ for ft, fc, tt, tc in meta["fkcols"]:
272
+ if ft.lower() in shown and tt.lower() in shown and ft.lower() != tt.lower():
273
+ ln = f"{ft}.{fc} = {tt}.{tc}"
274
+ if ln not in lines:
275
+ lines.append(ln)
276
+ return ("\n\nTable relationships (join keys):\n" + "\n".join(lines)) if lines else ""
277
+
278
+
279
+ # ------------------------------------------------------------------ alias repair
280
+ def alias_repair(sql: str, db: str) -> str | None:
281
+ """If a qualified column isn't on its table but exists on exactly one other table in the query,
282
+ re-qualify it. Returns the repaired SQL, or None if nothing changed / not parseable."""
283
+ meta = db_meta(db)
284
+ cols_of = {t.lower(): {c.lower() for c, _ in cs} for t, cs in meta["tables"].items()}
285
+ try:
286
+ tree = sqlglot.parse_one(sql, read="sqlite")
287
+ except Exception: # noqa: BLE001
288
+ return None
289
+ changed = False
290
+ for select in tree.find_all(exp.Select):
291
+ alias_to_table = {}
292
+ for t in select.find_all(exp.Table):
293
+ if t.find_ancestor(exp.Select) is not select:
294
+ continue
295
+ alias_to_table[(t.alias or t.name).lower()] = t.name.lower()
296
+ for col in select.find_all(exp.Column):
297
+ if col.find_ancestor(exp.Select) is not select or not col.table:
298
+ continue
299
+ q, name = col.table.lower(), col.name.lower()
300
+ t = alias_to_table.get(q)
301
+ if t is None or t not in cols_of or name in cols_of[t]:
302
+ continue
303
+ owners = [a for a, tt in alias_to_table.items() if tt in cols_of and name in cols_of[tt]]
304
+ if len(owners) == 1:
305
+ col.set("table", exp.to_identifier(owners[0]))
306
+ changed = True
307
+ continue
308
+ if owners:
309
+ continue
310
+ # join completion: the column lives in a table one FK hop from this alias's table
311
+ tables_l = {tt.lower(): tt for tt in meta["tables"]}
312
+ cands = []
313
+ for other, ocols in cols_of.items():
314
+ if name in ocols and other not in alias_to_table.values():
315
+ keys = join_keys(db, tables_l[t], tables_l[other])
316
+ if keys:
317
+ cands.append((other, keys))
318
+ if len(cands) != 1:
319
+ continue
320
+ other, (ka, kb) = cands[0]
321
+ new_alias = f"J{len(alias_to_table) + 1}"
322
+ on = exp.EQ(this=exp.column(ka, table=col.table), expression=exp.column(kb, table=new_alias))
323
+ select.set("joins", (select.args.get("joins") or []) + [exp.Join(
324
+ this=exp.Table(this=exp.to_identifier(tables_l[other]), alias=exp.TableAlias(
325
+ this=exp.to_identifier(new_alias))), on=on, kind="INNER")])
326
+ alias_to_table[new_alias.lower()] = other
327
+ col.set("table", exp.to_identifier(new_alias))
328
+ changed = True
329
+ return tree.sql(dialect="sqlite") if changed else None
330
+
331
+
332
+
333
+
334
+ def repair_sql(sql: str, db: str, max_rounds: int = 3) -> str | None:
335
+ """Apply alias repair / join completion repeatedly (multi-hop joins). None if nothing changed."""
336
+ cur, changed = sql, False
337
+ for _ in range(max_rounds):
338
+ new = alias_repair(cur, db)
339
+ if not new or new == cur:
340
+ break
341
+ cur, changed = new, True
342
+ return cur if changed else None
343
+
344
+
345
+ # ------------------------------------------------------------------ value snapping
346
+ def _norm_val(s: str) -> str:
347
+ return re.sub(r"\s+", " ", re.sub(r"[^\w\s]", "", s.lower())).strip()
348
+
349
+
350
+ def _most_common(con, q, vals):
351
+ """Unique value, or the most frequent spelling when the candidates differ only in letter case."""
352
+ if not vals or len({v.lower() for v in vals}) != 1:
353
+ return None
354
+ if len(vals) == 1:
355
+ return vals[0]
356
+ return max(vals, key=lambda v: con.execute(f"SELECT COUNT(*) FROM {q[0]} WHERE {q[1]} = ?", (v,)).fetchone()[0])
357
+
358
+
359
+ def _snap_one(con, t, c, lit, is_str):
360
+ """-> replacement value for `t.c = lit` when lit does not occur in the column, else None (unique match only)."""
361
+ q = f'"{t}"', f'"{c}"'
362
+ try:
363
+ if con.execute(f"SELECT 1 FROM {q[0]} WHERE {q[1]} = ? LIMIT 1", (lit,)).fetchone():
364
+ return None
365
+ if not is_str: # number literal: a text column like 'YR2002' that ends with it
366
+ rows = con.execute(f"SELECT DISTINCT {q[1]} FROM {q[0]} WHERE typeof({q[1]})='text' "
367
+ f"AND {q[1]} LIKE ? LIMIT 3", (f"%{lit}",)).fetchall()
368
+ vals = [v for (v,) in rows if re.fullmatch(rf"[A-Za-z]{{0,4}}[\s\-_]?{re.escape(str(lit))}", v)]
369
+ return _most_common(con, q, vals)
370
+ rows = con.execute(f"SELECT DISTINCT {q[1]} FROM {q[0]} WHERE lower({q[1]}) = lower(?) LIMIT 5",
371
+ (lit,)).fetchall()
372
+ if rows:
373
+ return _most_common(con, q, [v for (v,) in rows])
374
+ n = _norm_val(lit)
375
+ if not n:
376
+ return None
377
+ rows = con.execute(f"SELECT DISTINCT {q[1]} FROM {q[0]} WHERE typeof({q[1]})='text' "
378
+ f"LIMIT {MAX_DISTINCT_PER_COL}").fetchall()
379
+ vals = [v for (v,) in rows if _norm_val(v) == n]
380
+ return vals[0] if len(vals) == 1 else None
381
+ except (sqlite3.Error, OverflowError, ValueError): # e.g. an integer literal too large for SQLite
382
+ return None
383
+
384
+
385
+ def snap_values(sql: str, db: str) -> str | None:
386
+ """Replace literals that do not occur in their column with the unique near-identical stored value
387
+ (case, punctuation/spacing, 'YR'-style prefixes), and `col IS NULL` with `col = ''` when the column
388
+ has no NULLs but has empty strings. Returns the new SQL, or None if nothing changed."""
389
+ meta = db_meta(db)
390
+ cols_of = {t.lower(): (t, {c.lower(): c for c, _ in cs}) for t, cs in meta["tables"].items()}
391
+ try:
392
+ tree = sqlglot.parse_one(sql, read="sqlite")
393
+ except Exception: # noqa: BLE001
394
+ return None
395
+ con = _con(db)
396
+ changed = False
397
+
398
+ def owner(col, select):
399
+ amap = {}
400
+ for t in select.find_all(exp.Table):
401
+ if t.find_ancestor(exp.Select) is select and t.name.lower() in cols_of:
402
+ amap[(t.alias or t.name).lower()] = t.name.lower()
403
+ name = col.name.lower()
404
+ if col.table:
405
+ t = amap.get(col.table.lower())
406
+ return (cols_of[t][0], cols_of[t][1][name]) if t and name in cols_of[t][1] else None
407
+ hits = [t for t in set(amap.values()) if name in cols_of[t][1]]
408
+ return (cols_of[hits[0]][0], cols_of[hits[0]][1][name]) if len(hits) == 1 else None
409
+
410
+ try:
411
+ for node in list(tree.find_all(exp.EQ, exp.In, exp.Is)):
412
+ select = node.find_ancestor(exp.Select)
413
+ if select is None:
414
+ continue
415
+ if isinstance(node, exp.Is):
416
+ col = node.this
417
+ if not (isinstance(col, exp.Column) and isinstance(node.expression, exp.Null)) \
418
+ or isinstance(node.parent, exp.Not):
419
+ continue
420
+ o = owner(col, select)
421
+ if not o:
422
+ continue
423
+ t, c = o
424
+ r = con.execute(f'SELECT SUM("{c}" IS NULL), SUM("{c}" = \'\') FROM "{t}"').fetchone()
425
+ if r and not r[0] and r[1]:
426
+ node.replace(exp.EQ(this=col.copy(), expression=exp.Literal.string("")))
427
+ changed = True
428
+ continue
429
+ if isinstance(node, exp.EQ):
430
+ pairs = [(node.this, node.expression)] if isinstance(node.this, exp.Column) else \
431
+ [(node.expression, node.this)] if isinstance(node.expression, exp.Column) else []
432
+ lits = [(col, l) for col, l in pairs if isinstance(l, exp.Literal)]
433
+ else:
434
+ lits = [(node.this, l) for l in node.expressions if isinstance(node.this, exp.Column)
435
+ and isinstance(l, exp.Literal)]
436
+ for col, lit in lits:
437
+ o = owner(col, select)
438
+ if not o:
439
+ continue
440
+ val = lit.this if lit.is_string else (int(lit.this) if lit.this.lstrip("-").isdigit() else None)
441
+ if val is None or (lit.is_string and len(val) < 2):
442
+ continue
443
+ new = _snap_one(con, o[0], o[1], val, lit.is_string)
444
+ if new is not None and new != val:
445
+ lit.replace(exp.Literal.string(new))
446
+ changed = True
447
+ finally:
448
+ con.close()
449
+ return tree.sql(dialect="sqlite") if changed else None
generator/adapter_config.json ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "peft_type": "LORA",
3
+ "task_type": "CAUSAL_LM",
4
+ "base_model_name_or_path": "Qwen/Qwen2.5-Coder-1.5B-Instruct",
5
+ "r": 16,
6
+ "lora_alpha": 16.0,
7
+ "lora_dropout": 0.0,
8
+ "bias": "none",
9
+ "target_modules": [
10
+ "down_proj",
11
+ "gate_proj",
12
+ "k_proj",
13
+ "o_proj",
14
+ "q_proj",
15
+ "up_proj",
16
+ "v_proj"
17
+ ],
18
+ "layers_to_transform": [
19
+ 1,
20
+ 2,
21
+ 3,
22
+ 4,
23
+ 5,
24
+ 6,
25
+ 7,
26
+ 8,
27
+ 9,
28
+ 10,
29
+ 11,
30
+ 12,
31
+ 13,
32
+ 14,
33
+ 15,
34
+ 16,
35
+ 17,
36
+ 18,
37
+ 19,
38
+ 20,
39
+ 21,
40
+ 22,
41
+ 23,
42
+ 24,
43
+ 25,
44
+ 26,
45
+ 27
46
+ ],
47
+ "fan_in_fan_out": false,
48
+ "inference_mode": true,
49
+ "use_rslora": false,
50
+ "use_dora": false,
51
+ "init_lora_weights": true,
52
+ "modules_to_save": null
53
+ }
generator/adapter_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:46ea48c5a9926c4379897f80a2aa3915290d9d709064c51bcf0f19d1cae82588
3
+ size 71271408
mlx/generator/adapter_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "base_model": "Qwen/Qwen2.5-Coder-1.5B-Instruct",
3
+ "fine_tune_type": "lora",
4
+ "num_layers": 27,
5
+ "lora_parameters": {
6
+ "rank": 16,
7
+ "scale": 1.0,
8
+ "dropout": 0.05
9
+ }
10
+ }
mlx/generator/adapters.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a3bf0907652e90c81f5bb4815d2a5891180816ae773a8e79339e1be2407c2e98
3
+ size 71262322
mlx/verifier/adapter_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "base_model": "Qwen/Qwen2.5-Coder-1.5B-Instruct",
3
+ "fine_tune_type": "lora",
4
+ "num_layers": 27,
5
+ "lora_parameters": {
6
+ "rank": 16,
7
+ "scale": 1.0,
8
+ "dropout": 0.05
9
+ }
10
+ }
mlx/verifier/adapters.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:121d21744cb7737e1def6ae87ee14d641034c96a8876708c8009a07fc37cccb3
3
+ size 71262322
verifier/adapter_config.json ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "peft_type": "LORA",
3
+ "task_type": "CAUSAL_LM",
4
+ "base_model_name_or_path": "Qwen/Qwen2.5-Coder-1.5B-Instruct",
5
+ "r": 16,
6
+ "lora_alpha": 16.0,
7
+ "lora_dropout": 0.0,
8
+ "bias": "none",
9
+ "target_modules": [
10
+ "down_proj",
11
+ "gate_proj",
12
+ "k_proj",
13
+ "o_proj",
14
+ "q_proj",
15
+ "up_proj",
16
+ "v_proj"
17
+ ],
18
+ "layers_to_transform": [
19
+ 1,
20
+ 2,
21
+ 3,
22
+ 4,
23
+ 5,
24
+ 6,
25
+ 7,
26
+ 8,
27
+ 9,
28
+ 10,
29
+ 11,
30
+ 12,
31
+ 13,
32
+ 14,
33
+ 15,
34
+ 16,
35
+ 17,
36
+ 18,
37
+ 19,
38
+ 20,
39
+ 21,
40
+ 22,
41
+ 23,
42
+ 24,
43
+ 25,
44
+ 26,
45
+ 27
46
+ ],
47
+ "fan_in_fan_out": false,
48
+ "inference_mode": true,
49
+ "use_rslora": false,
50
+ "use_dora": false,
51
+ "init_lora_weights": true,
52
+ "modules_to_save": null
53
+ }
verifier/adapter_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e3b5359c206a2252e236a8443030b937e65270d44e1c4543f3d50f747c304312
3
+ size 71271408