#!/usr/bin/env python3 # build_qa_compact.py —— 考释问答紧凑版(Fable 22:35 裁定)+ 第二阶段回放集 # QA:保留问题头(【材料片段】之前全部),材料片段只留答案引用到的 [#k],外加每种片段类型(括号标签)至多 1 条未引用的靠前片段; # 每条片段正文截到 ≤300 字;原 [#k] 编号不改(答案原样可用);9B 分词 + chat 模板计 token,须 ≤2,000, # 超了先把片段截到 200 字、再去掉未引用片段,仍超则弃行。 # 回放:U_zh_v1 中随机 今译 2,500 + 断句 1,500(种子 20260923)。 # 输出:data/qa_kaoshi_v1_compact.jsonl、data/replay_v1.jsonl、data/stage2_v1.jsonl(两者合并打乱)+ 各自 .READY,收据 receipts/stage2_v1.receipt.json import json, re, random, hashlib, collections, datetime, statistics from transformers import AutoTokenizer W = "/root/autodl-tmp/llm_rag_20261023"; TOK = "/root/autodl-tmp/llm_sft_20260918/models/Qwen3.5-9B" tok = AutoTokenizer.from_pretrained(TOK) LIM = 2000 def ntok(msgs): r = 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) BLK = re.compile(r"^\[#(\d+)\] ", re.M) def split_user(u): i = u.find("【材料片段】") if i < 0: return u, None, [] head = u[:i]; rest = u[i:] first = rest.split("\n", 1)[0] # 【材料片段】共 N 条: body = rest[len(first):] ms = list(BLK.finditer(body)); blocks = [] for j, m in enumerate(ms): end = ms[j + 1].start() if j + 1 < len(ms) else len(body) txt = body[m.start():end].rstrip("\n") k = int(m.group(1)); line1, _, rest_ = txt.partition("\n") tag = re.search(r"(([A-Za-z_]+))\s*$", line1); tag = tag.group(1) if tag else "?" blocks.append({"k": k, "head": line1, "body": rest_.strip(), "tag": tag}) tail = body[ms[-1].end():] if False else "" return head, first, blocks def build(head, blocks, cut): parts = ["%s\n%s" % (b["head"], (b["body"][:cut] + ("……" if len(b["body"]) > cut else ""))) for b in blocks] return head + "【材料片段】共 %d 条(节选):\n\n" % len(blocks) + "\n\n".join(parts) + "\n" qa = [json.loads(l) for l in open(W + "/data/qa_kaoshi_v1.jsonl", encoding="utf-8")] idx = [json.loads(l) for l in open(W + "/data/qa_kaoshi_v1.index.jsonl", encoding="utf-8")] out = []; st = collections.Counter(); toks = []; src_kept = collections.Counter() for o, ix in zip(qa, idx): sysm, usr, ans = [next(m for m in o["messages"] if m["role"] == r) for r in ("system", "user", "assistant")] head, first, blocks = split_user(usr["content"]) if not blocks: st["no_blocks_parsed"] += 1; continue cited = set(int(x) for x in re.findall(r"\[#(\d+)\]", ans["content"])) keep, seen_tag = [], set() for b in blocks: if b["k"] in cited: keep.append(b) elif b["tag"] not in seen_tag and len([x for x in keep if x["k"] not in cited]) < 3: keep.append(b); seen_tag.add(b["tag"]) missing = cited - {b["k"] for b in keep} if missing: st["cited_block_missing"] += 1; continue msgs = None for cut, drop_uncited in ((300, False), (200, False), (200, True), (120, True)): kb = [b for b in keep if (b["k"] in cited or not drop_uncited)] m2 = [{"role": "system", "content": sysm["content"]}, {"role": "user", "content": build(head, kb, cut)}, {"role": "assistant", "content": ans["content"]}] n = ntok(m2) if n <= LIM: msgs = m2; st["fit_cut%d%s" % (cut, "_citedonly" if drop_uncited else "")] += 1; break if msgs is None: st["drop_over_limit"] += 1; continue toks.append(n); out.append({"messages": msgs}); src_kept[ix.get("source", "?")] += 1 rng = random.Random(20260923) prov = [json.loads(l) for l in open(W + "/data/U_zh_v1.prov.jsonl", encoding="utf-8")] U = open(W + "/data/U_zh_v1.jsonl", encoding="utf-8").read().splitlines() zh = [i for i, p in enumerate(prov) if p["comp"] == "zh"]; pu = [i for i, p in enumerate(prov) if p["comp"].startswith("punct")] rep_idx = rng.sample(zh, 2500) + rng.sample(pu, 1500) rep = [json.loads(U[i]) for i in rep_idx] rep_tok = [ntok(r["messages"]) for r in rep] rep_ok = [r for r, n in zip(rep, rep_tok) if n <= 2048] def wr(p, rows): with open(p, "w", encoding="utf-8") as f: for r in rows: f.write(json.dumps(r, ensure_ascii=False) + "\n") h = hashlib.sha256(open(p, "rb").read()).hexdigest(); open(p + ".READY", "w").write(h + "\n"); return h h1 = wr(W + "/data/qa_kaoshi_v1_compact.jsonl", out) h2 = wr(W + "/data/replay_v1.jsonl", rep_ok) allr = out + rep_ok; rng.shuffle(allr); h3 = wr(W + "/data/stage2_v1.jsonl", allr) q = lambda a, p: sorted(a)[int(p * (len(a) - 1))] if a else None rc = {"qa_compact": {"file": W + "/data/qa_kaoshi_v1_compact.jsonl", "rows": len(out), "sha256": h1, "in_rows": len(qa), "stats": dict(st), "by_source": dict(src_kept), "tokens": {"median": statistics.median(toks) if toks else None, "p90": q(toks, .9), "max": max(toks) if toks else None, "limit": LIM}, "rule": "保留问题头;材料片段只留答案所引 [#k] + 每种标签至多 1 条未引用片段(总未引用 ≤3);片段正文 ≤300 字(不够再 200/仅引用/120);编号不改;9B chat 模板 ≤2,000 token,否则弃行"}, "replay": {"file": W + "/data/replay_v1.jsonl", "rows": len(rep_ok), "sha256": h2, "zh": 2500, "punct": 1500, "seed": 20260923, "dropped_over_2048": len(rep) - len(rep_ok), "src": "U_zh_v1(sha 8486ed51…)"}, "stage2": {"file": W + "/data/stage2_v1.jsonl", "rows": len(allr), "sha256": h3}, "stage1_note": "U_zh_v1 第一阶段:考释问答 4,232 行全部 >2,048 token(中位 5,042),ms-swift truncation_strategy=delete 编码时静默删除 → 第一阶段臂 0 条考释问答;开卷 28,176 行中 1,195 行 >2,048 同被删除 → 实训开卷 26,981 行", "license": "internal_only", "training_release": False, "created_at": datetime.datetime.now().isoformat(timespec="seconds")} json.dump(rc, open(W + "/receipts/stage2_v1.receipt.json", "w", encoding="utf-8"), ensure_ascii=False, indent=1) print(json.dumps({k: (v if k != "stage1_note" else "...") for k, v in rc.items() if k in ("qa_compact", "replay", "stage2")}, ensure_ascii=False, indent=1))