nv-kgmad / scripts /pilot_v2.py
eduzrh's picture
Upload NV-KGMAD code, data, cached responses, results and paper (part 8)
372dc01 verified
Raw History Blame Contribute Delete
5.96 kB
#!/usr/bin/env python3
"""Pilot: does an explicit budget ledger make KGMAD's hypotheses better?
Runs a two-round role debate (the ablation-optimal setting), then asks the
model to converge into a hypothesis whose numeric constraints are closed in a
machine-checkable ledger. Any unclosed row is fed back for repair.
Usage:
python scripts/pilot_v2.py T01 T05 T07
"""
from __future__ import annotations
import json
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from nvkgmad.agents import _constraints, _short, run_kgmad # noqa: E402
from nvkgmad.config import LLMConfig # noqa: E402
from nvkgmad.corpus import load_topics # noqa: E402
from nvkgmad.knowledge_graph import load_kb # noqa: E402
from nvkgmad.llm import LLMClient # noqa: E402
from nvkgmad.verify_ledger import check_ledgers, ledger_issues # noqa: E402
FINAL_V2 = """【研究主题】{title}
【问题描述】{problem}
【工程约束】{constraints}
【辩论共识草案】
{draft}
【可引用文献】{allowed_refs}
请把上述材料收敛为一个单一、完整、可执行的技术假设,总长度 1200~1500 字。
必须包含以下小节(用【】标注):
【问题与瓶颈】2~3 句,点明被干预的核心物理量及其与约束的冲突。
【核心机制】用“因为…因此…从而…”的因果链说明。**至多 3 个机制**;每个机制必须写出它与另一个机制的接口量(热流、隔离度、时序、光斑等)。
【跨学科方案】三段:光学/材料、微波/IC、封装/系统。每段写结构、材料/器件、关键工艺,段末写出交给下一层的接口参数。
【预算账本】针对上面每一条**带数值的工程约束**,各写一行,格式严格如下(用 Markdown 表格,四列,不要增减列):
| 预算 | 分项 | 合计 | 约束 |
|---|---|---|---|
| 功耗/mW | 微波 40 + 激光 35 + 读出 20 | 95 | ≤100 |
| 面积/mm² | 微波 0.5 + 光电 0.6 + 数字 0.9 | 2.0 | ≤2.0 |
规则:
- “分项”必须用 “名称 数值 + 名称 数值 + …” 的形式,数值不带单位(单位写在第一列);
- “合计”必须等于分项数值之和,且必须满足右列约束(≤ 或 ≥);
- 只能写能够求和或直接比较的量(功耗、面积、热流、时序预算、隔离度余量等);无法求和的指标(如灵敏度、线宽)不要写进账本。
【关键参数】5~7 行表格,三列:参数 | 目标值 | 依据。依据只能是以下三种之一:
(a) 证据编号 [R##],且该数值确实出现在该条证据中;
(b) 算式,如“4 mW × 20 K/W = 80 mK”;
(c) “待测定”。
不得出现无法归入这三类的数值。
【验证路径】2~3 步,每步写“测什么、怎么测、达到什么值算成功”。
【风险与备选】2 个风险及降级方案。
【证据基础】2~3 句,列出 4~8 个给定编号的引用。
要求:关键指标带单位;只引用给定编号;不得出现“可能”“或许”作为核心论证;直接以【问题与瓶颈】开头,不要说明修改过程。
"""
REPAIR_V2 = """下面这份假设的预算账本没有闭合:
{issues}
请在不改变核心机制的前提下重算这些账本行,使“分项之和 = 合计”且“合计满足约束”。
可以调整分项数值或改变分项构成,但不得改动其他小节的核心内容,也不得引入新的文献编号。
直接输出修订后的完整假设(保持原有【】小节,1200~1500 字),不要说明修改了什么。
原假设:
{hypothesis}
"""
def run(client: LLMClient, kb, topic: dict, max_repair: int = 2) -> dict:
trace = run_kgmad(client, kb, topic, rounds=2, verify=False)
text = client.complete(
"你是严谨的跨学科科学家,负责把辩论结果收敛为单一、可执行、预算闭合的科学假设。",
FINAL_V2.format(
title=topic["title"],
problem=topic["problem"],
constraints=_constraints(topic),
draft=_short(trace.drafts[-1], 1800),
allowed_refs=", ".join(trace.retrieved_refs),
),
tag=f"pilotv2:{topic['id']}:final",
max_tokens=3000,
temperature=0.45,
).text
history = []
for k in range(max_repair):
rows = check_ledgers(text)
issues = ledger_issues(rows)
history.append({"round": k, "rows": rows, "issues": issues})
if not issues:
break
text = client.complete(
"你是严谨的跨学科科学家,负责修正预算账本。",
REPAIR_V2.format(issues=";".join(issues[:4]), hypothesis=text),
tag=f"pilotv2:{topic['id']}:repair{k}",
max_tokens=3000,
temperature=0.3,
).text
rows = check_ledgers(text)
return {
"topic_id": topic["id"],
"topic_title": topic["title"],
"method": "kgmad_v2",
"method_label": "KGMAD v2(账本闭合)",
"text": text,
"retrieved_refs": trace.retrieved_refs,
"ledger": rows,
"ledger_issues": ledger_issues(rows),
"history": history,
}
def main() -> None:
ids = sys.argv[1:] or ["T01", "T05", "T07"]
client = LLMClient(LLMConfig())
kb = load_kb()
topics = {t["id"]: t for t in load_topics()}
out_dir = ROOT / "outputs" / "pilot_v2"
out_dir.mkdir(parents=True, exist_ok=True)
for tid in ids:
rec = run(client, kb, topics[tid])
path = out_dir / f"{tid}.json"
path.write_text(json.dumps(rec, ensure_ascii=False, indent=1), encoding="utf-8")
rows = rec["ledger"]
print(
f"{tid}: {len(rec['text'])} chars, {len(rows)} ledger rows, "
f"{sum(r['ok'] for r in rows)}/{len(rows)} closed, "
f"issues={rec['ledger_issues'][:2]}"
)
if __name__ == "__main__":
main()