#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""cs_post.py —— 传世考释问答 v1 · 生成后处理(CPU):vLLM 输出 → k27 格式 → 引文闸门(scripts/qa/k27/k27_filter.py,与考释 v1 同一个、同参数)
→ 末道泄漏检查(leak_gate:gatesets_v1 + 演示 76 简;训练 user + 回答;12-gram / ≥6 字包含 → 剔除;口径同 qa_post.py)
→ 换短训练系统提示 SYS_TRAIN + 训练 user(无【任务】段)→ ≤2,000 token 装箱(qa_v2_pack.fit;未引用块先截/删)→ SFT 文件 + 收据 + .READY。
产物:data/qa_chuanshi_v1.jsonl(.index.jsonl/.READY)、receipts/qa_chuanshi_v1.receipt.json
"""
import collections, hashlib, json, lzma, os, re, subprocess, sys, time, statistics
W = "/root/autodl-tmp/llm_rag_20261023"
D = os.environ.get("CS_D") or W + "/data/qa_cs"
OUT = os.environ.get("CS_OUT") or W + "/data/qa_chuanshi_v1.jsonl"
IDX = OUT.replace(".jsonl", ".index.jsonl")
RC = os.environ.get("CS_RC") or W + "/receipts/qa_chuanshi_v1.receipt.json"
QA = W + "/scripts/qa"; TOK = "/root/autodl-tmp/llm_sft_20260918/models/Qwen3.5-9B"
sys.path.insert(0, W + "/scripts"); sys.path.insert(0, W + "/scripts/qa_cs")
from cs_prompts_common import SYS_TRAIN
import qa_v2_pack as PK
THINK = re.compile(r".*?\s*", re.S)
LIM = 2000
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)
G = {}
def init():
from transformers import AutoTokenizer
from leak_gate import Gate
G["tok"] = AutoTokenizer.from_pretrained(TOK)
gate = Gate()
with lzma.open(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(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])
G["gate"] = gate
def ntok(msgs):
r = G["tok"].apply_chat_template(msgs, tokenize=True, add_generation_prompt=False)
r = r["input_ids"] if hasattr(r, "keys") else r
return len(r[0]) if (r and isinstance(r[0], list)) else len(r)
def one(args):
rid, tu, ans = args
hit, rag = set(), set()
for t in (tu, ans):
rej, info = G["gate"].check(t)
if info["hit12"] or info["contain"]:
for s in info["sets"]:
(rag if s.startswith("RAG_") else hit).add(s)
if hit: return rid, None, {"leak": sorted(hit)}
sp = PK.split_user(tu)
head, blocks, tail = sp
u, n, lvl, info = PK.fit(ntok, SYS_TRAIN, head, blocks, tail, ans, LIM, None)
meta = {"level": lvl, "n_tok": n, "n_blocks_in": len(blocks), "dropped_blocks": info.get("dropped", []), "cited_cap": info.get("cited_cap"),
"rag_hits": sorted(rag)}
if u is None: return rid, None, dict(meta, fail_fit=True)
cited = sorted(PK.cited_quotes(ans))
meta["cited"] = cited
meta["grounded_full"] = PK.grounded_ratio({b["k"]: b["body"] for b in blocks}, ans)
meta["grounded_visible"] = PK.grounded_ratio(info.get("vis") or {}, ans)
meta["name_full"] = PK.name_visible({b["k"]: b["body"] for b in blocks}, ans)
meta["name_visible"] = PK.name_visible(info.get("vis") or {}, ans)
return rid, {"messages": [{"role": "system", "content": SYS_TRAIN}, {"role": "user", "content": u}, {"role": "assistant", "content": ans}]}, meta
def main():
t0 = time.time()
prompts = D + "/prompts_cs_v1.jsonl"; gen = D + "/gen_out_cs_v1.jsonl"
P = {r["id"]: r for r in rd(prompts)}
Gn = rd(gen)
conv = D + "/gen_k27fmt_cs_v1.jsonl"; n_think = 0
with open(conv, "w", encoding="utf-8") as f:
for g in Gn:
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)" % (len(Gn), n_think))
raw = D + "/sft_gated_cs_v1.jsonl"; fst = D + "/FILTER_STATS_cs_v1.json"
cmd = [sys.executable, QA + "/k27/k27_filter.py", "--prompts", prompts, "--gen", conv, "--out", raw, "--stats", fst,
"--dropped-out", D + "/filter_dropped_cs_v1.jsonl", "--index-out", D + "/sft_gated_cs_v1.index.jsonl", "--with-id",
"--demo-core", W + "/vendor/release_demo_core_v1_2"]
env = dict(os.environ, PYTHONDONTWRITEBYTECODE="1", DEMO_CORE_DIR=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(fst, encoding="utf-8"))
kept = rd(raw)
log("gate kept %d / %d" % (len(kept), len(Gn)))
jobs = [(r["id"], P[r["id"]]["train_user"], r["messages"][2]["content"]) for r in kept]
from multiprocessing import Pool
with Pool(int(os.environ.get("PROCS", "40")), initializer=init) as pool:
res = pool.map(one, jobs, chunksize=8)
final, fix, leak, fitfail, leak_sets = [], [], 0, 0, collections.Counter()
for rid, row, m in res:
if row is None:
if m.get("leak"): leak += 1; leak_sets.update(m["leak"])
else: fitfail += 1
continue
p = P[rid]
final.append(row)
fix.append(dict({"line": len(final), "id": rid, "source": "cs_1024", "form": p["form"], "x_char": p.get("x_char"), "cite": p["cite"],
"work": p["work"], "pian": p.get("pian"), "chapter": p.get("chapter"), "block_ids": p["block_ids"],
"block_lanes": p["block_lanes"]}, **m))
assert all(m["n_tok"] <= LIM for m in fix)
tmp = OUT + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
for r in final: f.write(json.dumps(r, ensure_ascii=False) + "\n")
os.replace(tmp, OUT)
with open(IDX, "w", encoding="utf-8") as f:
for m in fix: f.write(json.dumps(m, ensure_ascii=False) + "\n")
assert sum(1 for _ in open(OUT, encoding="utf-8")) == len(final) == len(fix)
s = sha(OUT)
toks = sorted(m["n_tok"] for m in fix) or [0]
q = lambda a, p_: a[int(p_ * (len(a) - 1))]
G2 = {g["id"]: g for g in Gn}
gsum = None
gl = W + "/logs/qa_cs/gen.log"
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: gsum = json.loads(l)
except Exception: pass
samp = json.load(open(D + "/SAMPLE_STATS_cs_v1.json", encoding="utf-8"))
pst = json.load(open(D + "/PROMPT_STATS_cs_v1.json", encoding="utf-8"))
rmeta = [json.load(open(D + "/l2_cs_v1.jsonl.shard%d.meta.json" % k)) for k in range(16) if os.path.exists(D + "/l2_cs_v1.jsonl.shard%d.meta.json" % k)]
gen_forms = collections.Counter(P[g["id"]]["form"] for g in Gn if g["id"] in P)
kept_forms = collections.Counter(P[r["id"]]["form"] for r in kept)
lv = collections.Counter(m["level"] for m in fix)
rc_ = {"file": OUT, "rows": len(final), "sha256": s, "index": IDX, "license": "internal_only", "training_release": False,
"format": "messages (system=SYS_TRAIN 短提示(与 qa_kaoshi_v2_repack 同一条), user=【问题】+【材料片段】(原 [#k] 编号), assistant=过闸回答,保留 [#k])",
"plan": "PLAN_v4_NEXT24H_20261024.md §2 考释问答 v2 第二批(传世文献:A2 篇章 ↔ C 库诸家说)",
"system_prompt": SYS_TRAIN,
"pipeline": {"sample": "qa_cs/cs_sample.py(A2 主快照 epub 先秦两汉;去 B_dev 14 族、dev/eval_overlap;C 主快照 8-gram 引用锚 ≥1;门集 9 集 + 演示 76 简)",
"retrieve": "qa_cs/cs_retrieve.py 进程内 fls(线上 shards.json 只读 ft1+rr3):lib C{paper,related,collected}/main k16→装配 ≤5(锚 ≤2 优先)+ lib A2{classic,parallel} k8→≤2 他书文句;卡 2",
"prompts": "qa_cs/cs_build_prompts.py(块过滤同考释 v1:demo_core/TITLE_PAT/overlap/门集/quotable;训练格式 ≤1,480 token)",
"generate": "qa_cs/cs_vllm_gen.py Qwen3.8-27B 零样本 greedy rep1.0 MAXLEN 4096 MAX_NEW 600 TP1 卡 2;生成系统提示 SYS_GEN_CS(S6 改编,传世版)",
"gate": "scripts/qa/k27/k27_filter.py v1.0.0 默认参数(词面落地 + 演示核心包 v1_2 引文闸门 rapidfuzz partial_ratio≥90;两小标题、≥4 结论、过闸率 ≥0.6、非截断)",
"leak": "leak_gate 12-gram / ≥6 字包含 vs gatesets_v1(非 RAG_* 集)+ 演示 76 简,训练 user 与回答各查",
"pack": "qa_v2_pack.fit ≤2,000 token(9B chat 模板)"},
"counts": {"sampled": samp["n"], "retrieved": sum(1 for _ in open(D + "/l2_cs_v1.jsonl", encoding="utf-8")),
"prompts": pst["n_prompts"], "generated": len(Gn), "gate_kept": len(kept), "leak_dropped": leak, "fit_dropped": fitfail, "final": len(final)},
"retention": {"gate_kept_over_generated": round(len(kept) / max(1, len(Gn)), 4), "final_over_generated": round(len(final) / max(1, len(Gn)), 4),
"by_form_gate": {f: round(kept_forms[f] / max(1, gen_forms[f]), 4) for f in gen_forms},
"kaoshi_v1_reference": "考释 v1 gen_1023:3,422 / 5,600 = 0.611"},
"forms": {"generated": dict(gen_forms), "final": dict(collections.Counter(m["form"] for m in fix)),
"rule": "F_ju「《书》「…」这句话怎么理解、各家怎么说?」/ F_zi「《书》「…」中的「X」字在这里怎么训释?」(X 取自锚块训释标记前、本段内的非虚字;有 X 的段 random('20261024|cid') <0.5 取 F_zi)"},
"tokens": {"min": toks[0], "p10": q(toks, .1), "p50": q(toks, .5), "p90": q(toks, .9), "p99": q(toks, .99), "max": toks[-1],
"mean": round(statistics.mean(toks), 1) if fix else None, "limit": LIM},
"levels": dict(lv), "zero_block_trim_rows": lv.get("L0", 0),
"lexical_grounding": {"full": round(sum(m["grounded_full"][0] for m in fix) / max(1, sum(m["grounded_full"][1] for m in fix)), 4),
"visible": round(sum(m["grounded_visible"][0] for m in fix) / max(1, sum(m["grounded_visible"][1] for m in fix)), 4),
"name_lines_lost": sum(m["name_full"][0] - m["name_visible"][0] for m in fix)},
"by_work": dict(collections.Counter(m["work"] for m in fix).most_common()),
"leak_check": {"dropped_rows": leak, "by_set": dict(leak_sets), "rag_only_hits_rows_kept": sum(1 for m in fix if m.get("rag_hits"))},
"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")},
"sample_stats": {k: samp.get(k) for k in ("counts", "gate_hit_sets", "forms", "anchor_rule", "excl_work")},
"prompt_stats": pst, "retrieval_meta": rmeta[:1] + [{"shard": m.get("shard"), "n": m.get("n"), "sec": m.get("sec"), "stopped_at_deadline": m.get("stopped_at_deadline")} for m in rmeta[1:]],
"generation": gsum, "think_stripped": n_think,
"hit_max_generated": sum(1 for g in Gn if g.get("finish") == "length"),
"inputs_sha256": {"sample": sha(D + "/sample_cs_v1.jsonl"), "l2": sha(D + "/l2_cs_v1.jsonl"), "prompts": sha(prompts), "gen_out": sha(gen),
"gatesets_v1": sha(W + "/data/gatesets_v1.jsonl.xz")},
"scripts_sha256": {p_: sha(W + "/scripts/qa_cs/" + p_) for p_ in ("cs_sample.py", "cs_retrieve.py", "cs_build_prompts.py", "cs_prompts_common.py",
"cs_vllm_gen.py", "cs_gen_line.sh", "cs_post.py", "qa_v2_pack.py")},
"when": time.strftime("%Y-%m-%d %H:%M:%S"), "sec": round(time.time() - t0, 1)}
os.makedirs(os.path.dirname(RC), exist_ok=True)
json.dump(rc_, open(RC, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
open(OUT + ".READY", "w").write(s + "\n")
log("FINAL rows=%d sha=%s gate=%d/%d leak=%d fitfail=%d → %s" % (len(final), s, len(kept), len(Gn), leak, fitfail, OUT))
return 0
if __name__ == "__main__":
sys.exit(main())