EvoStream / evo2 /debug_one.py
SitongGong's picture
Add files using upload-large-folder tool
197d46b verified
Raw History Blame Contribute Delete
9.05 kB
"""单点调试入口:每个阶段都能单独跑一次,方便下断点。
配合 .vscode/launch.json 里的 evo2-2 / evo2-3 / evo2-4 / evo2-5 使用。
python evo2/debug_one.py qgen --dataset egoschema --space ACTION --time GLOBAL
python evo2/debug_one.py retrieve --question "Where did I put the screwdriver?"
python evo2/debug_one.py episode --pool data/pool_egoschema.json --index 0
python evo2/debug_one.py curate --kind fail
"""
import argparse
import json
import logging
import os
import sys
sys.path.insert(0, "/mnt/tokyo-ai/gst/EvoStream")
sys.path.insert(0, "/mnt/tokyo-ai/gst/EvoStream/cons_memory")
logging.basicConfig(level=logging.INFO, format="[%(levelname)s] %(message)s")
# ---------------------------------------------------------------- 出题
def cmd_qgen(a):
from infer.llm_clients import make_client
from memory_store import VideoMemory
from evo2.qgen import QuestionGenerator, phrasing_rule
from evo2.style_cards import build_style_card
from evo2.validate_qgen import list_banks, sample_frames
banks = list_banks(a.dataset, 3)
vid, bank = banks[a.video_idx]
mem = VideoMemory(bank)
mode = "global" if a.time == "GLOBAL" else "window"
frames, ts = sample_frames(mem, mode)
print(f"视频 {vid} | 采样 {mode} {len(frames)} 帧 @ "
f"{[f'{t:.0f}s' for t in ts]}")
print(f"\n--- 该格子的措辞约束 ---\n{phrasing_rule(a.time)}\n")
qg = QuestionGenerator(make_client(a.gen_ep, temperature=0.7),
make_client(a.verify_ep, temperature=0.0),
style_card=build_style_card(a.dataset))
rec = qg.make_one(frames, ts, a.space, a.time) # ← 断点打这里
print(json.dumps(rec, ensure_ascii=False, indent=1)[:2500])
print(f"\n结果: stage={rec['stage']} passed={rec['passed']} "
f"reject={rec.get('reject')}")
# ---------------------------------------------------------------- 检索
def cmd_retrieve(a):
from infer.llm_clients import embed_texts
from evo2.classifier import classify_lexical
from evo2.seed_lib import build_seed
from evo2.skill import SkillLibrary, keyword_score
lib = SkillLibrary(build_seed(a.seed_mode), embed_fn=embed_texts)
lib.index_library()
cell = classify_lexical(a.question, None) # ← 断点:题型判定
print(f"题目: {a.question}")
print(f"题型判定: {cell}")
cards, scores = lib.retrieve(a.question, cell, topk=len(lib.cards),
return_scores=True) # ← 断点:打分
print(f"\n全部卡片打分(前8):")
for s in scores[:8]:
print(f" {s['total']:.4f} = kw {s['kw']:.3f}*0.5 + sem {s['sem']:.3f}*0.5 "
f"(+先验) [{s['card_id']}]")
print(f"\n实际注入(top2): {[c['card_id'] for c in cards[:2]]}")
print("\n渲染给 executor 的文本:")
print(SkillLibrary.render(cards[:2]))
# ---------------------------------------------------------------- 单题推理
def cmd_episode(a):
from infer.config import RunConfig
from infer.llm_clients import embed_texts, make_client
from infer.tools import ToolRegistry
from evo2.pipeline import run_one_episode
from evo2.seed_lib import build_seed
from evo2.skill import SkillLibrary
from evo2.tracelog import TraceLogger
pool = json.load(open(a.pool))
qs = pool["train"] + pool["frozen_val"]
q = qs[a.index]
print(f"题目[{a.index}]: {q['question'][:140]}")
print(f" 格子={q['cell']} gt={q.get('gt')} video={q['video_id']}")
cfg = RunConfig()
cfg.executor = a.executor_ep
lib = SkillLibrary(build_seed(a.seed_mode), embed_fn=embed_texts)
lib.index_library()
vlm = make_client(cfg.vlm_tool, temperature=0.0)
tl = TraceLogger("/mnt/tokyo-ai/gst/EvoStream/runs/DEBUG_one")
log = run_one_episode(q, lib, make_client(a.executor_ep, temperature=0.0),
lambda m: ToolRegistry(m, cfg, vlm_client=vlm),
cfg, tl=tl, meta={"phase": "debug"}) # ← 断点
print("\n--- 工具轨迹 ---")
for s in (log.get("trace") or []):
print(f" {s['step']}. {s['tool']}({json.dumps(s['args'], ensure_ascii=False)[:90]})")
print(f" → {(s.get('result_digest') or '')[:180]}")
print(f"\n思考: {(log.get('reasoning') or '')[:400]}")
print(f"答案: {log.get('choice')} (gt={q.get('gt')}) 正确={log.get('correct')}")
print(f"注入的卡: {log.get('skills_injected')} adherence={log.get('adherence')}")
tl.close()
# ---------------------------------------------------------------- 归纳改卡
def cmd_curate(a):
from infer.llm_clients import make_client
from infer.tools import TOOL_SPECS
from evo2.curator import build_prompt, catalog_of
from evo2.gates import gate_all
from evo2.seed_lib import build_seed
from evo2.skill import new_card
# 构造轨迹:库里已有一张"只用文本检索"的缺陷卡,照做仍答错 → 应 modify
existing = [new_card("count-caption-only", ["how many", "count", "number of"],
"询问数量时用文本检索caption统计",
[{"tool": "get_topk_caption", "params": {"k": 5}}],
["COUNT"], ["NOW", "PAST"], "caption中提到了数量")] \
if a.with_existing else build_seed("empty")
fails = [
{"question": "How many times did the person rinse the pan?", "cell": "COUNT-PAST",
"trace": [{"tool": "get_topk_caption", "args": {"query": "rinse pan", "k": 5}}],
"skills_injected": [c["card_id"] for c in existing], "adherence": 1.0,
"failure_mode": "照策略执行了但caption未给出精确数量"},
{"question": "How many plates were on the rack?", "cell": "COUNT-NOW",
"trace": [{"tool": "get_topk_caption", "args": {"query": "plates", "k": 5}}],
"skills_injected": [c["card_id"] for c in existing], "adherence": 1.0,
"failure_mode": "照策略执行了但caption未给出精确数量"},
]
contrast = [
{"question": "Where did I put the blue screwdriver?", "cell": "SPATIAL-PAST",
"trace": [{"tool": "get_topk_caption", "args": {"query": "screwdriver"}}],
"outcome": "答错", "skills_injected": []},
{"question": "Where did I put the blue screwdriver?", "cell": "SPATIAL-PAST",
"trace": [{"tool": "get_topk_frame", "args": {"query": "screwdriver on bench"}},
{"tool": "rewatch_frames", "args": {"t_start": 88, "t_end": 108}}],
"outcome": "答对", "skills_injected": []},
]
eps = fails if a.kind == "fail" else contrast
specs = TOOL_SPECS if isinstance(TOOL_SPECS, str) else \
json.dumps(TOOL_SPECS, ensure_ascii=False)[:2500]
prompt = build_prompt(a.kind, eps, catalog_of(existing), specs,
n_cards=len(existing)) # ← 断点:看完整 prompt
print(f"--- prompt 长度 {len(prompt)} 字符(前1200)---\n{prompt[:1200]}\n...")
r = make_client(a.curator_ep, temperature=0.5).chat_json(prompt, max_tokens=4000) or {}
print(f"\n--- curator reasoning ---\n{str(r.get('reasoning'))[:600]}")
for op in (r.get("ops") or []):
card = op.get("card") or {}
if op.get("op") == "modify":
base = next((c for c in existing if c["card_id"] == op.get("card_id")), {})
card = {**base, **(op.get("changes") or {})}
ok, why = gate_all(card, existing, op.get("op", "add")) # ← 断点:过闸
print(f"\n[{op.get('op')}] {card.get('card_id')} 过闸={ok} {why}")
print(json.dumps(card, ensure_ascii=False, indent=1)[:900])
def main():
ap = argparse.ArgumentParser()
sub = ap.add_subparsers(dest="cmd", required=True)
p = sub.add_parser("qgen")
p.add_argument("--dataset", default="egoschema")
p.add_argument("--space", default="ACTION")
p.add_argument("--time", default="GLOBAL")
p.add_argument("--video-idx", type=int, default=0)
p.add_argument("--gen-ep", default="qwen38_pool")
p.add_argument("--verify-ep", default="qwen_local")
p.set_defaults(fn=cmd_qgen)
p = sub.add_parser("retrieve")
p.add_argument("--question", required=True)
p.add_argument("--seed-mode", default="minimal")
p.set_defaults(fn=cmd_retrieve)
p = sub.add_parser("episode")
p.add_argument("--pool", default="/mnt/tokyo-ai/gst/EvoStream/data/pool_egoschema.json")
p.add_argument("--index", type=int, default=0)
p.add_argument("--seed-mode", default="minimal")
p.add_argument("--executor-ep", default="qwen38_pool")
p.set_defaults(fn=cmd_episode)
p = sub.add_parser("curate")
p.add_argument("--kind", default="fail", choices=["fail", "success"])
p.add_argument("--with-existing", action="store_true", default=True)
p.add_argument("--curator-ep", default="qwen38_pool")
p.set_defaults(fn=cmd_curate)
a = ap.parse_args()
a.fn(a)
if __name__ == "__main__":
main()