Text Generation
PEFT
Safetensors
MLX
English
text-to-sql
sql
sqlite
lora
bird
spider
Eval Results (legacy)
File size: 6,542 Bytes
d2bec35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c35e40a
 
 
d2bec35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c35e40a
 
 
d2bec35
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
"""SQLant inference pipeline, independent of the model backend (PyTorch or MLX).

Per question (identical to the evaluated pipeline in the SQLant repository):
  1. draft    = generator, greedy, full-schema prompt
  2. prompt   = pruned schema (tables linked from question / evidence / matched values / draft SQL)
  3. cands    = generator on the pruned prompt: 1 greedy + 7 samples (T 0.8, top-p 0.95)
  4. execute  each candidate after SQL repair + value snapping (read-only, 15 s timeout)
  5. group    candidates by result rows; if >= 2 groups, the verifier scores one SQL per group
  6. pick     argmax  v + 1.5 * log(votes); if the pick returns no rows, the best group that returns rows
              (no executable candidate -> the greedy candidate)
"""
import hashlib
import json
import math
import re
import sqlite3
import time
from collections import defaultdict
from pathlib import Path

from . import schema_tools as S
from .schema_format import build_prompt, schema_text

SYSTEM = "You are an expert SQLite developer who writes correct, efficient SQL."
VSYS = "You are an expert SQLite reviewer. Decide whether the candidate SQL correctly answers the question."
N_SAMPLES, TEMP, TOP_P, MAX_TOKENS = 15, 0.8, 0.95, 512   # 1 greedy + 15 sampled = 16 candidates
SAMPLE_BATCH = 8   # samples per generate() call, bounds peak memory on long schemas
ALPHA = 1.0        # chosen on held-out-database questions for 16 candidates (results/cand16)
QUERY_TIMEOUT_S = 15


# ---------------------------------------------------------------- prompts
def full_prompt(db, question, evidence):
    return build_prompt(schema_text(Path(db)), question, evidence or None)


def pruned_prompt(db, question, evidence, draft_sql):
    hits = S.match_values(question, evidence or "", db)
    keep = S.link_tables(question, evidence or "", db, hits, draft_sql)
    return build_prompt(S.schema_text_subset(db, keep), question, evidence or None)


def chat_messages(user):
    return [{"role": "user", "content": f"{SYSTEM}\n\n{user}"}]


def extract_sql(text):
    text = re.sub(r"<think>.*?</think>", "", text, flags=re.S)
    blocks = re.findall(r"```(?:sql|sqlite)?\s*\n?(.*?)```", text, flags=re.S | re.I)
    if blocks:
        sql = blocks[-1]
    else:
        m = re.search(r"\b(WITH|SELECT)\b.*", text, flags=re.S | re.I)
        sql = m.group(0) if m else text
    sql = sql.strip()
    sql = re.sub(r"\A(?:[ \t]*--[^\n]*\n)+", "", sql + "\n").strip()
    if ";" in sql:
        sql = sql.split(";")[0]
    return sql.strip()


# ---------------------------------------------------------------- execution
def run_sql(db, sql, timeout=QUERY_TIMEOUT_S):
    con = sqlite3.connect(f"file:{db}?mode=ro", uri=True)
    con.text_factory = lambda b: b.decode(errors="replace")
    deadline = time.monotonic() + timeout
    con.set_progress_handler(lambda: 1 if time.monotonic() > deadline else 0, 10_000)
    try:
        return set(con.execute(sql).fetchall()), None
    except Exception as e:  # noqa: BLE001
        return None, f"{type(e).__name__}: {e}"[:200]
    finally:
        con.close()


def _norm(rows):
    return set(map(tuple, json.loads(json.dumps([list(t) for t in rows], default=str))))


def execute(db, sql):
    """repair + value snapping + run -> None (error) or {key, fixed, n_rows, preview}."""
    fixed = S.repair_sql(sql, db) or sql
    fixed = S.snap_values(fixed, db) or fixed
    rows, _ = run_sql(db, fixed)
    if rows is None:
        return None
    rows = sorted(_norm(rows), key=repr)
    return {"key": hashlib.sha1(repr(sorted(map(repr, rows))).encode()).hexdigest(),
            "fixed": fixed, "n_rows": len(rows), "preview": [list(r) for r in rows[:5]]}


# ---------------------------------------------------------------- verifier input
def fmt_result(r):
    def cell(c):
        s = "NULL" if c is None else str(c)
        return s if len(s) <= 60 else s[:57] + "..."
    if r["n_rows"] == 0:
        return "(no rows)"
    lines = [" | ".join(cell(c) for c in row) for row in r["preview"]]
    more = f"\n... ({r['n_rows']} rows in total)" if r["n_rows"] > len(r["preview"]) else f"\n({r['n_rows']} rows)"
    return "\n".join(lines) + more


def verifier_message(prompt, sql, res):
    prompt = prompt.split("\n\nWrite one SQLite query", 1)[0]
    return (f"{VSYS}\n\n{prompt}\n\nCandidate SQL:\n```sql\n{sql}\n```\n\n"
            f"Execution result (first rows):\n{fmt_result(res)}\n\nIs the candidate SQL correct? Answer yes or no.")


# ---------------------------------------------------------------- selection
def select(prompt, cands, results, score_fn):
    """cands[0] is the greedy candidate. results[i] = execute(...) or None. Returns (final_sql, info)."""
    g = defaultdict(list)
    for j, r in enumerate(results):
        if r is not None:
            g[r["key"]].append(j)
    if not g:
        return (results[0]["fixed"] if results[0] else cands[0]), {"groups": 0}
    groups = []
    for key, idx in g.items():
        res = results[idx[0]]
        v = score_fn(verifier_message(prompt, res["fixed"].strip(), res)) if len(g) > 1 else 0.0
        groups.append({"key": key, "votes": len(idx), "first": idx[0], "v": v, "n_rows": res["n_rows"]})
    s = lambda x: x["v"] + ALPHA * math.log(x["votes"])  # noqa: E731
    best = max(groups, key=s)
    if best["n_rows"] == 0:  # empty-result rule
        ok = [x for x in groups if x["n_rows"] > 0 and not _zero_null(results[x["first"]])]
        best = max(ok, key=s) if ok else best
    return results[best["first"]]["fixed"].strip(), {"groups": len(groups), "picked": best}


def _zero_null(r):  # flag_rule.flag == "zero/null" -> not "ok", so not a fallback target
    p = r["preview"]
    return r["n_rows"] == 1 and len(p[0]) == 1 and p[0][0] in (0, None)


def answer(backend, db, question, evidence):
    """Full pipeline for one question. backend: generate(messages, n, temp) -> [texts]; score(user) -> float."""
    draft = extract_sql(backend.generate(chat_messages(full_prompt(db, question, evidence)), 1, 0.0)[0])
    prompt = pruned_prompt(db, question, evidence, draft)
    msgs = chat_messages(prompt)
    texts = backend.generate(msgs, 1, 0.0)
    for k in range(0, N_SAMPLES, SAMPLE_BATCH):
        texts += backend.generate(msgs, min(SAMPLE_BATCH, N_SAMPLES - k), TEMP)
    cands = [extract_sql(t) for t in texts]
    results = [execute(db, c) for c in cands]
    final, info = select(prompt, cands, results, backend.score)
    return {"sql": final, "draft": draft, "candidates": cands, "groups": info.get("groups", 0)}