File size: 5,263 Bytes
94da461
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
"""Capture C3 reasoning for the STILL-CAUGHT remediated rows, then bucket the

tells so we can see what C3 is still catching them on.



Rebuilds the exact same prompt/orientation used in the scored run (baseline

answer_key), calls the judge once per row for its reasoning, writes

out/C3_remediated_caught_reasons.jsonl, and prints a tell-bucket histogram.



Run: python -u temp/story_remediation/analyze_caught.py

"""
from __future__ import annotations
import json, logging, re, sys
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import yaml

for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"):
    logging.getLogger(_n).setLevel(logging.WARNING)

HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[1]
sys.path.insert(0, str(ROOT))
from datasetreview import pipelines as P            # noqa: E402
from datasetreview import judge_prompts as J        # noqa: E402
from datasetreview.llm_client import make_judge      # noqa: E402

OUT = HERE / "out"
cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8"))
base = {json.loads(l)["item_id"]: json.loads(l)
        for l in open(ROOT / "datasetreview" / "results" / "new" / "C3.jsonl", encoding="utf-8") if l.strip()}
remed = {r["example_id"]: r for r in
         (json.loads(l) for l in open(OUT / "trajectories_remediated.jsonl", encoding="utf-8") if l.strip())}
scored = {json.loads(l)["item_id"]: json.loads(l)
          for l in open(OUT / "C3_remediated.jsonl", encoding="utf-8") if l.strip()}
caught_ids = [iid for iid, r in scored.items() if r.get("caught")]

reals = P.real_trajectories()
pairer = P.make_pairer(reals)
judge = make_judge(cfg["model"])

# tell buckets -> keyword patterns matched against reasoning about the fake side
BUCKETS = {
    "bundled_multitask":   r"multi[- ]?task|multiple (distinct|separate) |several (distinct|requests)|checklist|enumerat|packs|laundry list|bundl",
    "too_precise_ids":     r"exact (order|id|item)|precise|order number|conveniently|front[- ]?load|all the details|specific ids|recites|recite",
    "no_backforth_dense":  r"no back[- ]?and[- ]?forth|dense|rapid|single (turn|message)|one (turn|message|go)|without (any )?clarif|immediately|right away|opening (message|turn)",
    "invented_capability": r"unusual (request|task|service)|would not (typically|normally)|no real|not (a )?(typical|standard|common)|niche|obscure|rare (request|service)|atypical",
    "agent_overconfident": r"agent (volunteer|claims|asserts|states)|policy|without (verif|confirm|authenticat)|overconfident|too confident|proactively",
    "scripted_synthetic":  r"synthetic|constructed|engineered|scripted|test scenario|designed to|artificial|contrived|crafted|feels? (fake|off|unnatural)|too (tidy|neat|clean|smooth|polished)|stilted|robotic",
    "verification_flow":   r"verif|authenticat|identity|name and zip|otp|one[- ]?time code",
}


def which_side_is_fake(key):
    return "A" if key == "A" else "B"


def one(iid):
    fake = remed[iid]; b = base.get(iid)
    real = pairer(fake)
    swap = (b or {}).get("answer_key") == "B"
    msgs = J.build_c3(fake, real, swap=swap)
    try:
        r = judge.judge({"system": msgs["system"], "user": msgs["user"]})
    except Exception as e:  # noqa
        return {"item_id": iid, "error": str(e)}
    return {"item_id": iid, "answer_key": msgs["answer_key"], "guess": r.get("guess"),
            "confidence": r.get("confidence"), "reasoning": r.get("reasoning", ""),
            "fake_side": which_side_is_fake(msgs["answer_key"])}


def main():
    print(f"capturing reasoning for {len(caught_ids)} still-caught rows...")
    with ThreadPoolExecutor(max_workers=8) as ex:
        res = list(ex.map(one, caught_ids))
    res = [r for r in res if not r.get("error")]
    (OUT / "C3_remediated_caught_reasons.jsonl").write_text(
        "\n".join(json.dumps(r) for r in res) + "\n", encoding="utf-8")

    bucket = Counter(); multi = Counter(); conf = Counter()
    per_row = []
    for r in res:
        txt = (r.get("reasoning") or "").lower()
        conf[r.get("confidence")] += 1
        hits = [name for name, pat in BUCKETS.items() if re.search(pat, txt)]
        if not hits:
            hits = ["other_unbucketed"]
        for h in hits:
            bucket[h] += 1
        multi[len(hits)] += 1
        per_row.append((r["item_id"], r.get("confidence"), hits))

    n = len(res)
    print(f"\nreasoning captured: {n}   (confidence: {dict(conf)})")
    print("\n=== WHY STILL CAUGHT: tell buckets (rows whose reasoning cites each; multi-count) ===")
    for name, c in bucket.most_common():
        print(f"  {name:22s} {c:3d}  ({c/n:.0%})")
    print("\n=== tells per row ===", dict(sorted(multi.items())))
    # sample a few high-confidence catches verbatim
    print("\n=== sample HIGH-confidence catches (verbatim reasoning) ===")
    hi = [r for r in res if r.get("confidence") == "high"][:6]
    for r in hi:
        print(f"\n[{r['item_id']}] fake={r['fake_side']} guess={r['guess']}")
        print("   " + (r.get("reasoning") or "")[:400])


if __name__ == "__main__":
    main()