File size: 5,714 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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
"""SANDBOX C3 (large): position-invariant dual-orientation run over 102 items

(51 humanized injected rows + their 51 host rows), samples=3 per orientation =

612 judgments. Re-judging the hosts in THIS run makes before/after apples-to-apples

(same judge instance, same pairing), removing run-to-run variance vs the stored

baseline. Crash-safe: appends each finished item to out/c3_big_results.jsonl.

Canonical files are read-only.



Run from repo root:  python -u temp/injection_sandbox/run_c3_big.py

"""
from __future__ import annotations

import json
import logging
import threading
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from statistics import mean

import yaml

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

import sys
ROOT = Path(__file__).resolve().parents[2]
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

SAND = Path(__file__).resolve().parent
OUT = SAND / "out"
MERGED = OUT / "_staging_merged_injections.jsonl"
PROV = json.load(open(OUT / "_merged_injections.prov.json", encoding="utf-8"))
BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl"
RESULTS = OUT / "c3_big_results.jsonl"

cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8"))
SAMPLES = 3

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

injected = [json.loads(l) for l in open(MERGED, encoding="utf-8") if l.strip()]
c3 = {r["example_id"]: r for r in
      (json.loads(l) for l in open(SAND / "data" / "c3_trajectories.jsonl", encoding="utf-8") if l.strip())}
host_of = {p["example_id"]: p["host_of"] for p in PROV}
hosts = [c3[h] for h in dict.fromkeys(host_of.values())]   # unique, order-preserving

items = ([("injected", r) for r in injected]
         + [("host", r) for r in hosts])

_lock = threading.Lock()
_done = {}
if RESULTS.exists():                               # resume support
    for line in RESULTS.read_text(encoding="utf-8").splitlines():
        if line.strip():
            d = json.loads(line)
            _done[(d["group"], d["example_id"])] = d


def majority_guess(fake, real, swap):
    msgs = J.build_c3(fake, real, swap=swap)
    key = msgs["answer_key"]
    gs = []
    for _ in range(SAMPLES):
        try:
            gs.append(judge.judge({"system": msgs["system"], "user": msgs["user"]}).get("guess"))
        except Exception:                          # noqa: BLE001
            pass
    if not gs:
        return None, key, gs
    return Counter(gs).most_common(1)[0][0], key, gs


def run_item(group, fake):
    eid = fake["example_id"]
    if (group, eid) in _done:
        return _done[(group, eid)]
    real = pairer(fake)
    per = {}
    for name, swap in (("A", False), ("B", True)):   # fake in A, then fake in B
        maj, key, gs = majority_guess(fake, real, swap)
        per[name] = {"guess": maj, "answer_key": key, "caught": (maj == key), "samples": gs}
    catches = [per["A"]["caught"], per["B"]["caught"]]
    rec = {"group": group, "example_id": eid, "real_id": real.get("example_id"),
           "order_avg_catch": mean(1.0 if c else 0.0 for c in catches),
           "consistent_catch": all(catches), "any_catch": any(catches),
           "A": per["A"], "B": per["B"]}
    with _lock:
        with open(RESULTS, "a", encoding="utf-8") as f:
            f.write(json.dumps(rec) + "\n")
    return rec


def summarize(recs, group):
    g = [r for r in recs if r["group"] == group]
    n = len(g)
    if not n:
        return
    oa = mean(r["order_avg_catch"] for r in g)
    cons = sum(r["consistent_catch"] for r in g) / n
    a_only = sum(r["A"]["caught"] for r in g) / n
    print(f"  {group:9} n={n}  order-avg caught={oa:.1%}  "
          f"consistent(both orders)={cons:.1%}  orientation-A caught={a_only:.1%}")


def main():
    todo = [it for it in items if (it[0], it[1]["example_id"]) not in _done]
    print(f"items total={len(items)} (already done={len(_done)}) to-judge={len(todo)}  "
          f"orientations=2 samples={SAMPLES}  -> ~{len(todo)*2*SAMPLES} live calls")
    with ThreadPoolExecutor(max_workers=cfg["run"].get("workers", 4)) as ex:
        list(ex.map(lambda it: run_item(*it), todo))

    recs = [json.loads(l) for l in RESULTS.read_text(encoding="utf-8").splitlines() if l.strip()]
    print("\n=== C3 LARGE RESULT (dual-orientation, samples=3 majority) ===")
    summarize(recs, "injected")
    summarize(recs, "host")

    base = {}
    for line in open(BASELINE, encoding="utf-8"):
        if line.strip():
            d = json.loads(line)
            base[d.get("item_id")] = d.get("caught")
    base_all = [v for v in base.values() if v is not None]
    inj = [r for r in recs if r["group"] == "injected"]
    hos = [r for r in recs if r["group"] == "host"]
    print(f"\n  stored-baseline corpus (795): {sum(base_all)}/{len(base_all)} = {sum(base_all)/len(base_all):.1%}")
    if inj and hos:
        oi = mean(r["order_avg_catch"] for r in inj)
        oh = mean(r["order_avg_catch"] for r in hos)
        print(f"  same-run host order-avg caught:     {oh:.1%}")
        print(f"  same-run injected order-avg caught: {oi:.1%}")
        print(f"  injection+humanization effect (same hosts): {oi-oh:+.1%}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())