File size: 8,254 Bytes
788274d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9bd6473
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
788274d
9bd6473
788274d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9bd6473
788274d
9bd6473
788274d
 
 
 
 
 
 
 
 
 
 
 
 
 
9bd6473
788274d
 
 
 
 
 
 
9bd6473
 
 
 
 
 
 
 
 
 
 
 
 
 
 
788274d
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
143
144
145
146
147
148
149
150
151
152
153
154
"""Confirmatory held-out tables for one cell: per-run and pooled (r2+r3) paired, template-clustered CIs.

Pooling resamples whole templates jointly across runs, so within-template correlation across runs and
seeds is kept. Primary preregistered comparison: C6 vs C4b (target rate).

    python scripts/confirmatory_table.py runs/remote-all/heldout/tiny-vangogh results/confirmatory-tiny-vangogh
"""

from __future__ import annotations

import json
import sys
from pathlib import Path

import pandas as pd

from uvw.stats import cluster_bootstrap_ci, paired_cluster_bootstrap_diff

def selected_from_manifest(model: str, concept: str, runs=(2, 3)) -> tuple[dict, dict]:
    """Selected checkpoint per stochastic run (C4b/C5/C6, runs `runs`) and per deterministic baseline,
    read from the archive manifest, so the table always uses the rule-v1 choices."""
    from huggingface_hub import hf_hub_download

    rows = [json.loads(l) for l in Path(hf_hub_download(
        "javadtaghia/unlearning-via-weight-evals", "archive/manifest.jsonl", repo_type="dataset",
        force_download=True)).read_text().splitlines() if l.strip()]
    sel = {r["run_id"]: (r["path"], (r.get("selection") or {}).get("selected")) for r in rows
           if r["path"].startswith(f"{model}/{concept}/")}

    def pick(run_id: str) -> str | None:
        path, cand = sel.get(run_id, (None, None))
        return f"{path}/{cand}" if path and cand else None

    stochastic = {c: [pick(f"{c.lower()}-{model}-{concept}-r{i}") for i in runs] for c in ("C6", "C5", "C4b")}
    def only_candidate(run_id: str) -> str | None:
        """Ineligible single-candidate runs (ESD) are still reported: use the run's one candidate."""
        row = next((r for r in rows if r["run_id"] == run_id), None)
        cands = sorted({k.split("/")[-2] for k in (row or {}).get("files", {}) if k.startswith("model:")})
        return f"{row['path']}/{cands[0]}" if row and len(cands) == 1 else None

    reference = {"C1": "original",
                 # UCE with no eligible setting (tiny x church) is still reported: its official default
                 "C2": pick(f"c2-uce-{model}-{concept}") or next((f"{r['path']}/uce-default" for r in rows
                                                               if r["run_id"] == f"c2-uce-{model}-{concept}"), None),
                 "C3": pick(f"c3-esd-{model}-{concept}") or only_candidate(f"c3-esd-{model}-{concept}")}
    return stochastic, reference


RUNS: dict = {}
REFERENCES: dict = {}
RUN_NUMBERS: tuple = (2, 3)
METRICS_BY_CONCEPT = {  # label: (suite, role, column); Van Gogh unchanged from the published tables
    "vangogh": {
        "target rate": ("vangogh-test", "target", "target_hit"),
        "target rate (CLIP-H)": ("vangogh-test", "target", "clip_h14_hit"),
        "indirect probes": ("vangogh-probes", "target", "target_hit"),
        "neighbour correct": ("vangogh-test", "neighbour", "neighbour_correct"),
        "neighbour CLIP": ("vangogh-test", "neighbour", "clip_score"),
        "COCO CLIP": ("coco-test", None, "clip_score"),
    },
    "church": {
        "target rate": ("church-test", "target", "target_hit"),            # ResNet-50 top-1 = church
        "target rate (CLIP)": ("church-test", "target", "second_hit"),     # CLIP zero-shot = church
        "neighbour correct": ("church-test", "neighbour", "neighbour_correct"),
        "neighbour CLIP": ("church-test", "neighbour", "clip_score"),
        "COCO CLIP": ("coco-test", None, "clip_score"),
    },
    "nudity": {
        "target rate": ("nudity-test", "target", "target_hit"),            # Falconsai (primary, amendment)
        "target rate (NudeNet)": ("nudity-test", "target", "second_hit"),  # NudeNet (secondary)
        "benign flagged": ("nudity-test", "neighbour", "target_hit"),      # over-blocking proxy; lower is better
        "neighbour CLIP": ("nudity-test", "neighbour", "clip_score"),
        "COCO CLIP": ("coco-test", None, "clip_score"),
    },
}
METRICS = METRICS_BY_CONCEPT["vangogh"]
N_BOOT = 10_000


def load(root: Path, ckpt: str, label: str) -> pd.DataFrame:
    suite, role, col = METRICS[label]
    df = pd.read_json(root / ckpt / suite / "scores.jsonl", lines=True)
    if role:
        df = df[df.role == role]
    df = df[df[col].notna()]
    return df[["prompt_id", "seed", "group_id", col]].rename(columns={col: "y"})


def paired_frame(root: Path, a: str, b: str, label: str) -> pd.DataFrame:
    m = load(root, a, label).merge(load(root, b, label), on=["prompt_id", "seed"], suffixes=("_a", "_b"),
                                   validate="one_to_one")
    assert (m.group_id_a == m.group_id_b).all()
    return m


def diff(frames: list[pd.DataFrame]) -> dict:
    m = pd.concat(frames, ignore_index=True)
    d, lo, hi, p = paired_cluster_bootstrap_diff(m.y_a.astype(float), m.y_b.astype(float), m.group_id_a, n_boot=N_BOOT)
    return {"diff": d, "lo": lo, "hi": hi, "p": p, "n": len(m)}


def absolute(root: Path, ckpts: list[str], label: str) -> dict:
    df = pd.concat([load(root, c, label) for c in ckpts], ignore_index=True)
    m, lo, hi = cluster_bootstrap_ci(df.y.astype(float), df.group_id, n_boot=N_BOOT)
    return {"mean": m, "lo": lo, "hi": hi, "n": len(df)}


def main(root: Path, out: Path) -> None:
    res: dict = {"absolute": {}, "differences": {}}
    for cond, ck in REFERENCES.items():
        res["absolute"][cond] = {l: absolute(root, [ck], l) for l in METRICS}
    for cond, runs in RUNS.items():
        for i, ck in zip(RUN_NUMBERS, runs):
            res["absolute"][f"{cond} r{i}"] = {l: absolute(root, [ck], l) for l in METRICS}
        res["absolute"][f"{cond} pooled " + "+".join(f"r{i}" for i in RUN_NUMBERS)] = {l: absolute(root, runs, l) for l in METRICS}
    comparisons = [(c, ref) for c in RUNS for ref in ("C1", "C2", "C3")] + [("C6", "C4b"), ("C6", "C5")]
    for a, b in comparisons:
        key = f"{a} − {b}"
        res["differences"][key] = {}
        for label in METRICS:
            if b in RUNS:  # run-paired: r2 vs r2, r3 vs r3
                frames = [paired_frame(root, ra, rb, label) for ra, rb in zip(RUNS[a], RUNS[b])]
            else:
                frames = [paired_frame(root, ra, REFERENCES[b], label) for ra in RUNS[a]]
            res["differences"][key][label] = diff(frames)
    out.with_suffix(".json").write_text(json.dumps(res, indent=2))
    lines = ["| condition | " + " | ".join(METRICS) + " |", "|---|" + "---|" * len(METRICS)]
    for cond, v in res["absolute"].items():
        lines.append(f"| {cond} | " + " | ".join(f"{v[l]['mean']:.3f} [{v[l]['lo']:.3f}, {v[l]['hi']:.3f}]" for l in METRICS) + " |")
    lines += ["", "| pooled " + "+".join(f"r{i}" for i in RUN_NUMBERS) + " difference | " + " | ".join(METRICS) + " |", "|---|" + "---|" * len(METRICS)]
    for key, v in res["differences"].items():
        lines.append(f"| {key} | " + " | ".join(f"{v[l]['diff']:+.3f} [{v[l]['lo']:+.3f}, {v[l]['hi']:+.3f}]" for l in METRICS) + " |")
    out.with_suffix(".md").write_text("\n".join(lines) + "\n")
    print("\n".join(lines))


if __name__ == "__main__":
    # usage: confirmatory_table.py <heldout root> <out stem> [model concept]
    if len(sys.argv) >= 5:
        METRICS = METRICS_BY_CONCEPT[sys.argv[4]]
        if len(sys.argv) >= 6:  # e.g. "1,2,3" when every run is confirmatory (post-freeze cells)
            RUN_NUMBERS = tuple(int(x) for x in sys.argv[5].split(","))
        RUNS, REFERENCES = selected_from_manifest(sys.argv[3], sys.argv[4], RUN_NUMBERS)
    else:  # tiny x vangogh, as first published
        RUNS = {"C6": ["tiny/vangogh/C6/c6-tiny-vangogh-r2/vg_preserve_regularized",
                       "tiny/vangogh/C6/c6-tiny-vangogh-r3/vg_value_rewrite_r10"],
                "C5": ["tiny/vangogh/C5/c5-tiny-vangogh-r2/vg_value_remap_bounded",
                       "tiny/vangogh/C5/c5-tiny-vangogh-r3/vg_key_value_regularized"],
                "C4b": ["tiny/vangogh/C4b/c4b-tiny-vangogh-r2/c4b-00",
                        "tiny/vangogh/C4b/c4b-tiny-vangogh-r3/c4b-08"]}
        REFERENCES = {"C1": "original", "C2": "tiny/vangogh/C2/c2-uce-tiny-vangogh/uce-preserve-x2",
                      "C3": "tiny/vangogh/C3/c3-esd-tiny-vangogh/esd-esd-x"}
    main(Path(sys.argv[1]), Path(sys.argv[2]))