#!/usr/bin/env python3 # -*- coding: utf-8 -*- """qa_post.py —— 考释问答 v1 · 生成后处理(CPU):vLLM 输出 → k27 格式 → 引文闸门(k27_filter.py,原样)→ 末道泄漏检查 → SFT 文件 + 收据 + .READY。 闸门 = 9 月 k27_filter.py v1.0.0(一字不改):① 逐行词面落地(≥2 个双字组见于所引块,扣本简自带文本); ② 演示核心包 v1_2 report.apply_citation_gate(引用编号存在、引语为所引块近似子串 rapidfuzz partial_ratio ≥90、 学者/年份/简号须在块内、quotable=false 块不得长引…);留样:两小标题齐、过闸后 ≥4 条结论行、过闸率 ≥0.6、非截断。 训练目标 = 过闸后仍存活的原行(保留 [#k])。 产物:W/data/qa_kaoshi_v1.jsonl(messages: system/user/assistant)、W/data/qa_kaoshi_v1.index.jsonl(同行序元数据)、 W/receipts/qa_kaoshi_v1.receipt.json、W/data/qa_kaoshi_v1.jsonl.READY(= sha256)。 """ import collections, hashlib, json, lzma, os, re, subprocess, sys, time W = "/root/autodl-tmp/llm_rag_20261023" D = os.environ.get("QA_D") or os.path.join(W, "data", "qa") QA = os.path.join(W, "scripts", "qa") PY = sys.executable _OD = os.environ.get("QA_OUTDIR") # 只给冒烟用;正式不设 OUT = os.path.join(_OD or os.path.join(W, "data"), "qa_kaoshi_v1.jsonl") IDX = os.path.join(_OD or os.path.join(W, "data"), "qa_kaoshi_v1.index.jsonl") RCPT = os.path.join(_OD or os.path.join(W, "receipts"), "qa_kaoshi_v1.receipt.json") sys.path.insert(0, os.path.join(W, "scripts")) from leak_gate import Gate, residual # noqa: E402 THINK = re.compile(r".*?\s*", re.S) def sha(p): h = hashlib.sha256() with open(p, "rb") as f: for b in iter(lambda: f.read(1 << 20), b""): h.update(b) return h.hexdigest() def rd(p): return [json.loads(l) for l in open(p, encoding="utf-8") if l.strip()] def log(m): print("%s %s" % (time.strftime("%H:%M:%S"), m), flush=True) def main(): prompts = os.path.join(D, "prompts_v1.jsonl") gen = os.path.join(D, "gen_out_v1.jsonl") P = {r["id"]: r for r in rd(prompts)} G = rd(gen) conv = os.path.join(D, "gen_k27fmt_v1.jsonl") n_think = 0 with open(conv, "w", encoding="utf-8") as f: for g in G: t = g.get("hyp") or "" if "" in t: n_think += 1 t = THINK.sub("", t) f.write(json.dumps({"id": g["id"], "text": t.strip(), "hit_max": g.get("finish") == "length", "n_new_tokens": g.get("n_tok")}, ensure_ascii=False) + "\n") log("gen %d rows (think-stripped %d) → %s" % (len(G), n_think, conv)) raw_sft = os.path.join(D, "sft_gated_v1.jsonl") fstats = os.path.join(D, "FILTER_STATS_v1.json") cmd = [PY, os.path.join(QA, "k27", "k27_filter.py"), "--prompts", prompts, "--gen", conv, "--out", raw_sft, "--stats", fstats, "--dropped-out", os.path.join(D, "filter_dropped_v1.jsonl"), "--index-out", os.path.join(D, "sft_gated_v1.index.jsonl"), "--with-id", "--demo-core", os.path.join(W, "vendor", "release_demo_core_v1_2")] env = dict(os.environ, PYTHONDONTWRITEBYTECODE="1", DEMO_CORE_DIR=os.path.join(W, "vendor", "release_demo_core_v1_2")) rc = subprocess.call(cmd, env=env) if rc != 0: log("k27_filter rc=%d" % rc); return 4 FS = json.load(open(fstats, encoding="utf-8")) kept = rd(raw_sft) # ── 末道泄漏检查(LLM 评测门集 + 演示 76 简;整行 user+assistant;12-gram / ≥6 字包含 → 剔除) gate = Gate() req = ("eval_v1_255", "A_dev_clean441", "frag154", "B_dev_eval500") with lzma.open(os.path.join(W, "data", "gatesets_v1.jsonl.xz"), "rt", encoding="utf-8") as f: for l in f: r = json.loads(l) gate.add(r["set"], r.get("id"), r.get("text") or "") for r in rd(os.path.join(W, "vendor", "release_demo_core_v1_2", "data", "slips.jsonl")): for k in ("text_loose_punct", "text_strict_punct"): if r.get(k): gate.add("demo76", r["slip_key"], r[k]) final, leak_drop, leak_sets = [], 0, collections.Counter() for r in kept: u = r["messages"][1]["content"]; a = r["messages"][2]["content"] hit = set() for t in (u, a): rej, info = gate.check(t) if info["hit12"] or info["contain"]: hit |= set(s for s in info["sets"] if not s.startswith("RAG_")) if hit: leak_drop += 1; leak_sets.update(hit); continue final.append(r) n_new_final = len(final) for r in final: r["source"] = "gen_1023" # ── 并入 9 月 k27 过闸行(qa_k27_fold.py 产物;已同口径过门):source=k27_0921 k27p = os.path.join(W, "data", "qa", "k27_0921_rows.jsonl") k27_info = {"included": False} if os.environ.get("QA_NO_K27") != "1" and os.path.exists(k27p + ".READY") \ and open(k27p + ".READY").read().strip() == sha(k27p): k27rows = rd(k27p) for r in k27rows: P[r["id"]] = dict(r, n_blocks=r.get("n_blocks") or 0) final.extend(k27rows) k27_info = {"included": True, "file": k27p, "sha256": sha(k27p), "rows": len(k27rows), "stats": json.load(open(os.path.join(W, "data", "qa", "K27_FOLD_STATS.json"), encoding="utf-8"))} texts = [r["messages"][1]["content"] + "\n" + r["messages"][2]["content"] for r in final] res, flagged = residual(gate, texts) # 12-gram 专列(用户口径):每个门集被最终文件 12-gram 命中的行数 res12 = {k: v.get("hit12", 0) for k, v in res.items()} # ── 写 SFT 文件(messages only)+ 同序 index tmp = OUT + ".tmp" with open(tmp, "w", encoding="utf-8") as f, open(IDX, "w", encoding="utf-8") as fi: for r in final: f.write(json.dumps({"messages": r["messages"]}, ensure_ascii=False) + "\n") p = P[r["id"]] fi.write(json.dumps({"id": r["id"], "source": r.get("source"), "form": p["form"], "x_char": p.get("x_char"), "cite": p["cite"], "corpus_cn": p["corpus_cn"], "book": p.get("book"), "pian": p.get("pian"), "family_id": p.get("family_id"), "n_blocks": p["n_blocks"]}, ensure_ascii=False) + "\n") os.replace(tmp, OUT) s = sha(OUT) by_form = collections.Counter(P[r["id"]]["form"] for r in final) by_form_src = {src: dict(collections.Counter(P[r["id"]]["form"] for r in final if r.get("source") == src)) for src in ("gen_1023", "k27_0921")} by_book = collections.Counter(P[r["id"]].get("book") or P[r["id"]]["corpus_cn"] for r in final) by_pian = collections.Counter("%s|%s" % (P[r["id"]].get("book") or P[r["id"]]["corpus_cn"], P[r["id"]].get("pian")) for r in final) gen_forms = collections.Counter(P[g["id"]]["form"] for g in G if g["id"] in P) kept_forms = collections.Counter(P[r["id"]]["form"] for r in kept) samp = json.load(open(os.path.join(D, "SAMPLE_STATS.json"), encoding="utf-8")) pst = json.load(open(os.path.join(D, "PROMPT_STATS.json"), encoding="utf-8")) rmeta = [] for k in range(8): p = os.path.join(D, "l2_v1.jsonl.shard%d.meta.json" % k) if os.path.exists(p): rmeta.append(json.load(open(p, encoding="utf-8"))) gl = (os.path.join(D, "gen.log") if _OD else os.path.join(W, "logs", "qa", "gen.log")) gen_summary = None if os.path.exists(gl): for l in open(gl, encoding="utf-8", errors="replace"): if l.startswith("{") and '"tok_per_s"' in l: try: gen_summary = json.loads(l) except Exception: pass scripts = {} for fn in ("qa_k27_fold.py", "qa_sample.py", "qa_retrieve.py", "qa_build_prompts.py", "qa_post.py", "qa_retrieve_line.sh", "qa_gen.sh", "k27/k27_filter.py", "k27/k27_common.py", "k27/k27_build_prompts.py", "pipeline/report.py"): p = os.path.join(QA, fn) if os.path.exists(p): scripts[fn] = sha(p) rc_ = { "file": OUT, "rows": len(final), "sha256": s, "format": "messages (system, user=【问题】+演示 S6 上下文, assistant=过闸回答,保留 [#k])", "index": IDX, "license": "internal_only", "training_release": False, "plan": "PLAN_v3_ZH_CPT_KB_20261023.md §2.2 考释问答", "pipeline": {"sample": "qa_sample.py", "retrieve": "qa_retrieve.py --backend inproc (service/fls_core + fls_batch.run_record; 诸家说 lib C k=5 / 辞例 lib A / 传世对读 lib A2;线上 shards.json 只读:ft1 + rr3)", "prompts": "qa_build_prompts.py → k27_build_prompts.build_one → pipeline.report.build_messages_v2(release_demo_core_v1_2)", "generate": "vllm_gen.py Qwen3.8-27B 零样本 greedy rep1.0 MAXLEN 8192 MAX_NEW 768 TP1 GPU0", "gate": "k27_filter.py v1.0.0(词面落地 + 演示核心包 v1_2 引文闸门 rapidfuzz partial_ratio≥90)"}, "counts_by_source": dict(collections.Counter(r.get("source") for r in final)), "k27_0921": k27_info, "counts": {"slips_sampled": samp["n_units"], "prompts": pst["n_prompts"], "generated": len(G), "gate_kept": len(kept), "leak_dropped_final": leak_drop, "final_rows_gen_1023": n_new_final, "final_rows": len(final)}, "retention": {"gate_kept_over_generated": round(len(kept) / max(1, len(G)), 4), "final_over_generated": round(n_new_final / max(1, len(G)), 4), "by_form_gate": {f: round(kept_forms[f] / max(1, gen_forms[f]), 4) for f in gen_forms}, "september_k27_reference": "k27 FILTER_STATS 2026-09-21: 1,758/3,119 = 0.5636(任务书记作 66%)"}, "question_form_mix": {"sampled": samp["form_counts"], "prompts": pst["form_counts"], "generated": dict(gen_forms), "final": dict(by_form), "final_by_source": by_form_src, "rule": "每支简 random.Random('20261023|') 独立抽:F1 这支简怎么释读 / F2「X」字读为什么、各家怎么说(X=简内带通假或待考括注的字;无此类字的简不抽 F2)/ F3 与传世文献如何对读"}, "source_counts_by_book": dict(by_book.most_common()), "source_counts_by_pian": dict(by_pian.most_common()), "n_books": len(by_book), "n_pians": len(by_pian), "eval_residual": {"rule": "leak_gate.residual:门集每行被最终文件(user+assistant)12-gram 命中 / 6-gram 覆盖≥0.3 的行数", "hit12_by_set": res12, "full": res, "required_sets": list(req), "flagged_ids": {k: v[:20] for k, v in flagged.items()}, "final_forward_check": {"dropped_rows": leak_drop, "by_set": dict(leak_sets)}}, "exclusions": {"sample_stats": samp.get("dropped"), "gate_hits_by_set_at_sampling": samp.get("gate_hits_by_set"), "work_level": ["四篇:王家嘴《孔子曰》、枣纸简《吴王夫差起师伐越》《齐桓公自莒返于齐》、安大《仲尼曰》、群玉册府 QYCF14", "演示 76 简(release_demo_core_v1_2 slips.jsonl;= 演示 66 幅所涉简)", "A_dev_clean 441 族(GD_六位、SB_柬大王泊旱/陳公治兵/融師有成氏/相邦之道、QH_攝命/保训、GD_魯穆公問子思)", "越公其事(holdout)", "B_dev_eval 出土同族:睡虎地、马王堆老子甲乙本及卷前后古佚书(黄帝四经)、银雀山孙膑/孙子/尉缭子、郭店老子"], "k27_september": "9 月 k27 3,119 支经查是已训练集(kaoshi27b_train/val 切分 + stage1_sft.done,bjb1c)→ 排除:按 sample_id 1,604 块 + 他版同文(12-gram/6-gram/包含)", "context_blocks": pst.get("block_drop"), "context_block_gate_sets": pst.get("block_gate_sets")}, "filter_stats": {k: FS.get(k) for k in ("n_in", "n_kept", "keep_rate", "drop_reasons_primary", "gate_dropped_by_rule", "mean_claims_before", "mean_claims_after_kept", "section_lines_mean_kept", "fuzz_backend", "thresholds")}, "retrieval_meta": rmeta[:1] + [{"shard": m.get("shard"), "n": m.get("n"), "sec": m.get("sec"), "degraded_records": m.get("degraded_records")} for m in rmeta[1:]], "generation": gen_summary, "think_stripped": n_think, "inputs_sha256": {"slips_v1": sha(os.path.join(D, "slips_v1.jsonl")), "l2_v1": sha(os.path.join(D, "l2_v1.jsonl")), "prompts_v1": sha(prompts), "gen_in_v1": sha(os.path.join(D, "gen_in_v1.jsonl")), "gen_out_v1": sha(gen), "gatesets_v1": sha(os.path.join(W, "data", "gatesets_v1.jsonl.xz"))}, "scripts_sha256": scripts, "when": time.strftime("%Y-%m-%d %H:%M:%S"), } os.makedirs(os.path.dirname(RCPT), exist_ok=True) json.dump(rc_, open(RCPT, "w", encoding="utf-8"), ensure_ascii=False, indent=1) with open(OUT + ".READY", "w") as f: f.write(s + "\n") log("FINAL rows=%d (gen_1023 %d + k27_0921 %d) sha=%s retention(gate/gen)=%.4f leak_drop=%d → %s" % ( len(final), n_new_final, len(final) - n_new_final, s, len(kept) / max(1, len(G)), leak_drop, OUT)) return 0 if __name__ == "__main__": sys.exit(main())