Datasets:
Download scripts/infer.py from YukiKaze1337/cn-sqlite-sft: direct link, hf CLI and curl.
- Browser
- Download file 8.26 kB
-
https://huggingface.co/datasets/YukiKaze1337/cn-sqlite-sft/resolve/main/scripts/infer.py
- Command line
-
hf download hf://datasets/YukiKaze1337/cn-sqlite-sft/scripts/infer.py
-
curl -L -o infer.py https://huggingface.co/datasets/YukiKaze1337/cn-sqlite-sft/resolve/main/scripts/infer.py
8.26 kB
| """推理时的两个补救,eval.py 和 ask.py 共用: | |
| - repair:SQL 跑不通(报错、超时、抽不出 SQL)就把报错原文接在对话后面,让模型改,最多改 repair 次。 | |
| 第二轮剩下的错里,「no such column」这种跑不通的占一半,报错里写着哪一列不存在,模型对着建表语句能改对一部分 | |
| - vote:贪心 1 条 + 采样 vote-1 条,在同一个库上执行,结果一样的归一组,选最大的那组(一样大选含贪心那条的组); | |
| 都跑不通就用贪心那条,再交给 repair | |
| 两样都只看自己库上的执行结果,不看标准答案。评测时「自己的库」是生成的 5 份数据里的第一份。 | |
| 训练数据里没有「改错」这种多轮对话,模型是靠指令微调前的底子在改。 | |
| confidence() 用投票的一致程度判断把握:第二轮模型在两个难题集(164 题)上,5 条全一致的答对 91%(81/89), | |
| 3-4 条一致的 78%(31/40),2 条及以下的 31%(11/35)。所以默认 3 条以下一致就不给结果、跟用户说明。 | |
| 全一致也不等于一定对(89 题里错了 8 题):模型犯系统性的错时,几条会错得一模一样。 | |
| """ | |
| import sqlite3 | |
| from collections import Counter | |
| import eval as _ev | |
| from eval import _canon, extract_sql, rows_of | |
| FIX = "这条 SQL 执行出错:{err}\n对照建表语句改正,只输出改好的 SQL。" | |
| class Generator: | |
| """批量生成。sample=False 是贪心;sample=True 每题采样 n 条。""" | |
| def __init__(self, model: str, adapter: str = "", batch_size: int = 8, max_new_tokens: int = 1024): | |
| import torch | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| self.torch = torch | |
| self.tok = AutoTokenizer.from_pretrained(model) | |
| self.tok.padding_side = "left" # 批量生成要在左边补齐,新生成的 token 才接在真正的结尾后面 | |
| if self.tok.pad_token is None: | |
| self.tok.pad_token = self.tok.eos_token | |
| self.model = AutoModelForCausalLM.from_pretrained( | |
| model, torch_dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32, device_map="auto") | |
| if adapter: | |
| from peft import PeftModel | |
| self.model = PeftModel.from_pretrained(self.model, adapter).merge_and_unload() | |
| self.model.eval() | |
| self.batch_size = batch_size | |
| self.max_new_tokens = max_new_tokens | |
| def __call__(self, convs: list[list[dict]], n: int = 1, sample: bool = False) -> list[list[str]]: | |
| texts = [self.tok.apply_chat_template(c, tokenize=False, add_generation_prompt=True) for c in convs] | |
| if sample: | |
| self.torch.manual_seed(0) | |
| kw = dict(do_sample=True, temperature=0.7, top_p=0.9, top_k=50, num_return_sequences=n) | |
| else: | |
| kw = dict(do_sample=False, temperature=None, top_p=None, top_k=None) | |
| bs = max(1, self.batch_size // n) # 一次采样 n 条,批小一点,显存和贪心时差不多 | |
| out = [] | |
| for start in range(0, len(texts), bs): | |
| batch = self.tok(texts[start:start + bs], return_tensors="pt", padding=True).to(self.model.device) | |
| with self.torch.no_grad(): | |
| ids = self.model.generate(**batch, max_new_tokens=self.max_new_tokens, | |
| pad_token_id=self.tok.pad_token_id, **kw) | |
| dec = self.tok.batch_decode(ids[:, batch["input_ids"].shape[1]:], skip_special_tokens=True) | |
| k = n if sample else 1 | |
| out += [dec[i * k:(i + 1) * k] for i in range(len(dec) // k)] | |
| print(f"生成 {len(out)}/{len(texts)}" + (f"(每题 {n} 条)" if sample else ""), flush=True) | |
| return out | |
| def execute(conn: sqlite3.Connection, sql: str): | |
| """返回 (结果行, None) 或 (None, 报错)。报错原文会发回给模型,所以超时改成人话。""" | |
| if not sql: | |
| return None, "没有找到 SQL 语句" | |
| try: | |
| return rows_of(conn, sql), None | |
| except Exception as exc: # noqa: BLE001 | |
| msg = str(exc) | |
| if msg == "interrupted": | |
| msg = f"执行超过 {_ev.QUERY_TIMEOUT:.0f} 秒被中断,可能少了连接条件" | |
| return None, msg | |
| def _signature(rows) -> tuple: | |
| """结果的指纹:不管行的顺序,小数取 4 位。""" | |
| key = lambda r: tuple(round(v, 4) if isinstance(v, float) else v for v in r) | |
| return tuple(sorted(Counter(key(r) for r in _canon(rows)).items(), key=repr)) | |
| def pick_by_vote(candidates: list[str], conn: sqlite3.Connection) -> tuple[str, int]: | |
| """candidates[0] 是贪心那条。返回 (选中的 SQL, 同组票数)。""" | |
| groups: dict[tuple, list[int]] = {} | |
| for i, sql in enumerate(candidates): | |
| rows, err = execute(conn, sql) | |
| if err is None: | |
| groups.setdefault(_signature(rows), []).append(i) | |
| if not groups: | |
| return candidates[0], 0 | |
| best = max(groups.values(), key=lambda idx: (len(idx), 0 in idx)) | |
| return candidates[0 if 0 in best else best[0]], len(best) | |
| def answer(gen: Generator, convs: list[list[dict]], conns: list[sqlite3.Connection], | |
| repair: int = 0, vote: int = 1) -> list[dict]: | |
| """convs[i] 是第 i 题的 prompt(prompt.build 的输出),conns[i] 是它要查的库。 | |
| 返回每题 {"sql": 最终 SQL, "raw": 最后一次模型原话, "first_sql": 贪心第一条, "votes": 票数, "repairs": 改了几次}。""" | |
| greedy = [o[0] for o in gen(convs)] | |
| res = [{"sql": extract_sql(t), "raw": t, "first_sql": extract_sql(t), "votes": 1, "repairs": 0} for t in greedy] | |
| if vote > 1: | |
| samples = gen(convs, n=vote - 1, sample=True) | |
| for r, extra, conn in zip(res, samples, conns): | |
| r["sql"], r["votes"] = pick_by_vote([r["first_sql"]] + [extract_sql(t) for t in extra], conn) | |
| history = [list(c) for c in convs] | |
| for _ in range(repair): | |
| todo = [] | |
| for i, (r, conn) in enumerate(zip(res, conns)): | |
| _, err = execute(conn, r["sql"]) | |
| if err is not None: | |
| history[i] += [{"role": "assistant", "content": r["sql"] or r["raw"]}, | |
| {"role": "user", "content": FIX.format(err=err)}] | |
| todo.append(i) | |
| if not todo: | |
| break | |
| print(f"{len(todo)} 题跑不通,把报错发回去改", flush=True) | |
| for i, out in zip(todo, gen([history[i] for i in todo])): | |
| res[i].update(sql=extract_sql(out[0]), raw=out[0], repairs=res[i]["repairs"] + 1) | |
| return res | |
| def confidence(res: dict, conn: sqlite3.Connection, vote: int, min_votes: int) -> tuple[str, str]: | |
| """answer() 的一题结果有多大把握。返回 (等级, 给用户看的说明): | |
| high 全部一致 · medium 至少 min_votes 条一致 · low 一致的太少 · failed 改完还跑不通 · unknown 没投票,判断不了。 | |
| low 和 failed 不该把结果给用户。""" | |
| _, err = execute(conn, res["sql"]) | |
| if err is not None: | |
| return "failed", (f"没能写出能执行的查询(改了 {res['repairs']} 次还是报错:{err})。" | |
| "可能库里没有回答这个问题需要的表或字段,也可能问题要说得更具体。") | |
| if vote <= 1: | |
| return "unknown", "只写了 1 条,判断不了把握大不大;有 GPU 时加 --vote 5,会按几条结果是否一致给出可信度。" | |
| if res["votes"] == 0: | |
| return "low", (f"没把握,不回答:{vote} 条候选一开始都跑不通,改过之后才能跑,没法互相印证。" | |
| "可以把问题问得更具体,或者确认库里有回答它需要的信息。") | |
| if res["votes"] >= vote: | |
| return "high", f"把握较大:{vote} 条候选的执行结果全部一致。" | |
| if res["votes"] >= min_votes: | |
| return "medium", f"把握一般:{vote} 条候选里有 {res['votes']} 条结果一致,建议核对一下 SQL。" | |
| return "low", (f"没把握,不回答:{vote} 条候选的执行结果最多只有 {res['votes']} 条一致。" | |
| "可以把问题问得更具体(要哪几列、时间范围、并列怎么算),或者确认库里有回答它需要的信息。") | |