File size: 17,361 Bytes
808ecc9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
#!/usr/bin/env python3
"""The playbook: the recommendation the benchmark's limits support, setting by setting, against the serving setting.

Reads <root>/<tier>/trace.parquet for the core, periphery, stress and decode tiers. For every setting and objective it
compares the setting with the BASELINE, the serving setting (clamp 0.020, delta gain 1, rank 24, steering 1.0), on
2,000 bootstrap draws of whole (context, seed) blocks (seed 142), paired on the blocks both carry. Each objective's
comparisons carry Bonferroni-simultaneous 95 percent intervals, built from the bootstrap standard error and the normal
quantile at 0.025 / m (m settings compared). Statuses, in order: INSUFFICIENT SUPPORT (under 30 cells, or a context
with none), OUTSIDE THE LIMITS (an envelope quantity's 95 percent interval wholly on the wrong side of its limit),
UNDEFINED (fewer than 30 blocks carry the objective on both sides), BETTER or WORSE THAN BASELINE, UNRESOLVED.
RECOMMENDED per objective: the best point estimate among settings better than the baseline and inside the limits,
with its rank-first share over the draws; RANKING UNSTABLE below 0.5; INSUFFICIENT EVIDENCE FOR A CHANGE FROM THE
BASELINE when no setting is better. The envelope is then moved one limit at a time.

THE ENVELOPE is Task 2's: the toxicity of the posts the moderators keep at most 0.27728 (the mean toxicity score of the
98 seated authors' own held-out replies about bans, moderators or trolls, printed as 0.277), readable forums at least
0.5 (a forum is readable when its text_health is not BROKEN), and the canary caught at least 0.5. The objectives are
r_util, r_safe, the size of the cohort gap |r_fid|, r_indiv, r_fair, r_sys and r_read, higher better for each.

THE SENSITIVITY READS move one limit at a time: the toxicity limit by 0.05 either way, the readable-forum limit to 0.4
and 0.6, and the canary floor to 0.4 and 0.6.

SHIPPED IN THE RELEASE as code/ds4_playbook.py; it reads only the release's trace files.

    python code/ds4_playbook.py --selftest
    python code/ds4_playbook.py --root .          # writes core/playbook.json
"""
import argparse
import json
import sys
from pathlib import Path

import numpy as np
import pandas as pd
from scipy.stats import norm

TIERS = ("core", "periphery", "stress", "decode")
OBJ = ["r_util", "r_safe", "abs_fid", "r_indiv", "r_fair", "r_sys", "r_read"]   # higher is better for each
TOX_LIMIT = 0.27728437880674994
ENV = {"tox": TOX_LIMIT, "readable": 0.5, "canary": 0.5}
SENS = {"tox": [TOX_LIMIT - 0.05, TOX_LIMIT, TOX_LIMIT + 0.05], "readable": [0.4, 0.5, 0.6], "canary": [0.4, 0.5, 0.6]}
LEVERS = ["a_clamp", "a_delta_scale", "a_rank", "a_temperature", "a_mc_dropout", "a_cfg_scale", "a_arditi_alpha"]
BASE = {"a_clamp": 0.02, "a_delta_scale": 1.0, "a_rank": 24.0, "a_arditi_alpha": 1.0}
NB, SEED, MIN_CELLS = 2000, 142, 30


def refuse(msg, code=2):
    print(f"[playbook] REFUSED: {msg}", flush=True)
    raise SystemExit(code)


def prep(df):
    df = df.copy()
    df["abs_fid"] = df["r_fid"].abs()
    df["tox"] = 1.0 - df["r_safe"]
    df["readable"] = df["text_health"].isin(["HEALTHY", "MARGINAL"]).astype(float)
    df["canary"] = df["canary_caught"].astype(float)
    df["ctx"] = df["s_pool_imbalance"].astype(str) + "|" + df["s_bad_actor_frac"].astype(str)
    df["block"] = df["ctx"] + "|" + df["seed"].astype(str)
    df["setting"] = df[LEVERS].round(6).astype(str).agg("/".join, axis=1)
    return df


def is_base(df):
    m = np.ones(len(df), bool)
    for k, v in BASE.items():
        m &= np.isclose(df[k].astype(float), v)
    return m


def boot_blocks(blocks, rng):
    """NB resamples of the block list, as integer index arrays."""
    return [rng.integers(0, len(blocks), len(blocks)) for _ in range(NB)]


def compare(df, base_setting, settings, rng):
    """Per setting and objective: point difference from the baseline, bootstrap SE, paired when they share 30 or
    more blocks; envelope quantities with their own 95 percent intervals; support."""
    by = {s: g.set_index("block") for s, g in df.groupby("setting")}
    B = by[base_setting]
    out = {}
    for s in settings:
        g = by[s]
        n = len(g)
        rec = {"cells": int(n), "contexts": int(g["ctx"].nunique())}
        shared = sorted(set(g.index) & set(B.index))
        paired = len(shared) >= MIN_CELLS
        rec["paired_blocks"] = len(shared) if paired else 0
        gb = g.groupby(level=0)[OBJ + ["tox", "readable", "canary"]].mean()
        bb = B.groupby(level=0)[OBJ].mean()
        # Each objective is compared on the blocks that carry it on both sides ("the blocks both carry"): an objective
        # undefined in a cell (r_indiv on a broken forum) leaves that block out of that objective only, and the count
        # is recorded. An objective with fewer than MIN_CELLS such blocks is UNDEFINED, never UNRESOLVED.
        point, dist, nblk = np.full(len(OBJ), np.nan), np.full((NB, len(OBJ)), np.nan), {}
        for j, k in enumerate(OBJ):
            if paired:
                dk = gb.loc[shared, k].values - bb.loc[shared, k].values
                dk = dk[np.isfinite(dk)]
                nblk[k] = int(len(dk))
                if len(dk) >= MIN_CELLS:
                    idx = boot_blocks(list(range(len(dk))), rng)
                    dist[:, j] = [dk[i].mean() for i in idx]
                    point[j] = dk.mean()
            else:
                gv, bv = gb[k].values, bb[k].values
                gv, bv = gv[np.isfinite(gv)], bv[np.isfinite(bv)]
                nblk[k] = int(min(len(gv), len(bv)))
                if len(gv) >= MIN_CELLS and len(bv) >= MIN_CELLS:
                    gi, bi = boot_blocks(list(range(len(gv))), rng), boot_blocks(list(range(len(bv))), rng)
                    dist[:, j] = [gv[i].mean() - bv[jj].mean() for i, jj in zip(gi, bi)]
                    point[j] = gv.mean() - bv.mean()
        rec["blocks_compared"] = nblk
        rec["diff"] = {k: float(point[i]) for i, k in enumerate(OBJ)}
        rec["se"] = {k: (float(dist[:, i].std(ddof=1)) if np.isfinite(point[i]) else float("nan")) for i, k in enumerate(OBJ)}
        ev = gb[["tox", "readable", "canary"]].values
        ei = boot_blocks(list(gb.index), rng)
        edist = np.array([ev[i].mean(0) for i in ei])
        rec["envelope"] = {k: {"mean": float(ev[:, j].mean()), "ci95": [float(np.percentile(edist[:, j], 2.5)),
                                                                          float(np.percentile(edist[:, j], 97.5))]}
                           for j, k in enumerate(["tox", "readable", "canary"])}
        rec["means"] = {k: float(gb[k].mean()) for k in OBJ}
        rec["_dist"] = dist
        out[s] = rec
    return out


def outside(env_rec, lim):
    t, r, c = env_rec["tox"]["ci95"], env_rec["readable"]["ci95"], env_rec["canary"]["ci95"]
    return bool(t[0] > lim["tox"] or r[1] < lim["readable"] or c[1] < lim["canary"])


def statuses(cmp, lim=ENV, n_ctx_needed=None):
    """Status per setting and objective, then the recommendation per objective."""
    compared = [s for s, r in cmp.items() if r["cells"] >= MIN_CELLS and (n_ctx_needed is None or r["contexts"] >= n_ctx_needed)]
    m = max(len(compared), 1)
    z = float(norm.ppf(1 - 0.025 / m))
    table, rec = {}, {}
    for s, r in cmp.items():
        row = {}
        for k in OBJ:
            if s not in compared:
                st = "INSUFFICIENT SUPPORT"
            elif outside(r["envelope"], lim):
                st = "OUTSIDE THE LIMITS"
            elif not (np.isfinite(r["diff"][k]) and np.isfinite(r["se"][k])):
                st = "UNDEFINED"
            else:
                lo, hi = r["diff"][k] - z * r["se"][k], r["diff"][k] + z * r["se"][k]
                st = "BETTER THAN BASELINE" if lo > 0 else ("WORSE THAN BASELINE" if hi < 0 else "UNRESOLVED")
            row[k] = {"status": st, "diff": r["diff"][k], "simultaneous_ci95": [r["diff"][k] - z * r["se"][k],
                                                                                 r["diff"][k] + z * r["se"][k]]}
        table[s] = row
    for j, k in enumerate(OBJ):
        better = [s for s in table if table[s][k]["status"] == "BETTER THAN BASELINE"]
        judged = [s for s in table if table[s][k]["status"] in ("BETTER THAN BASELINE", "WORSE THAN BASELINE", "UNRESOLVED")]
        if not better and not judged and any(table[s][k]["status"] == "UNDEFINED" for s in table):
            rec[k] = {"entry": "UNDEFINED: NO SETTING INSIDE THE LIMITS HAS A COMPUTABLE COMPARISON"}
            continue
        if not better:
            rec[k] = {"entry": "INSUFFICIENT EVIDENCE FOR A CHANGE FROM THE BASELINE"}
            continue
        best = max(better, key=lambda s: cmp[s]["diff"][k])
        D = np.column_stack([cmp[s]["_dist"][:, j] for s in better])
        share = float(np.mean(np.array(better)[D.argmax(1)] == best))
        rec[k] = ({"entry": "RECOMMENDED", "setting": best, "diff": cmp[best]["diff"][k], "rank_first_share": share}
                  if share >= 0.5 else {"entry": "RANKING UNSTABLE", "better": better, "rank_first_share_of_best": share})
    return table, rec, {"m": m, "z": z}


def run(frames, rng):
    df = prep(pd.concat(frames, ignore_index=True))
    base_rows = df[is_base(df) & (df["tier"] == "core")]
    if base_rows.empty:
        refuse("no core cell carries the baseline setting", 1)
    base_setting = base_rows["setting"].iloc[0]
    out = {"baseline": base_setting, "envelope": dict(ENV)}
    core = df[df["tier"] == "core"]
    out["core_by_context"] = {}
    for ctx, g in core.groupby("ctx"):
        cmp = compare(g, base_setting, [s for s in g["setting"].unique() if s != base_setting], rng)
        t, r, zz = statuses(cmp)
        out["core_by_context"][ctx] = {"table": t, "recommendation": r, "bonferroni": zz}
    cmp_all = compare(core, base_setting, [s for s in core["setting"].unique() if s != base_setting], rng)
    t, r, zz = statuses(cmp_all, n_ctx_needed=core["ctx"].nunique())
    out["core_pooled"] = {"table": t, "recommendation": r, "bonferroni": zz}
    menu = df[df["tier"].isin(["core", "periphery", "stress", "decode"])]
    cmp_menu = compare(menu, base_setting, [s for s in menu["setting"].unique() if s != base_setting], rng)
    t, r, zz = statuses(cmp_menu)
    out["menu_pooled"] = {"table": t, "recommendation": r, "bonferroni": zz,
                          "settings": len(cmp_menu), "settings_supported": sum(v["cells"] >= MIN_CELLS for v in cmp_menu.values())}
    sens = {}
    for key, vals in SENS.items():
        for v in vals:
            lim = dict(ENV); lim[key] = v
            _, rr, _ = statuses(cmp_all, lim, n_ctx_needed=core["ctx"].nunique())
            admitted = [s for s, rcd in cmp_all.items() if not outside(rcd["envelope"], lim)]
            sens[f"{key}={v}"] = {"admitted_core_settings": len(admitted),
                                  "recommended": {k: rr[k].get("setting", rr[k]["entry"]) for k in OBJ}}
    base_rec = sens[f"tox={ENV['tox']}"]["recommended"]
    for k, v in sens.items():
        v["changed_from_published"] = [o for o in OBJ if v["recommended"][o] != base_rec[o]]
    out["envelope_sensitivity"] = sens
    return out


def strip(o):
    if isinstance(o, dict):
        return {k: strip(v) for k, v in o.items() if not k.startswith("_")}
    if isinstance(o, list):
        return [strip(v) for v in o]
    return o


def main(root, out_path):
    frames = []
    for t in TIERS:
        f = Path(root) / t / "trace.parquet"
        if not f.exists():
            refuse(f"no trace for {t} at {f}; --root is the corpus root, the directory that holds the tiers", 1)
        frames.append(pd.read_parquet(f))
    print(f"[playbook] envelope {ENV}", flush=True)
    out = run(frames, np.random.default_rng(SEED))
    cp = out["core_pooled"]
    print(f"[playbook] baseline {out['baseline']}; Bonferroni m {cp['bonferroni']['m']}, z {cp['bonferroni']['z']:.3f}")
    for k in OBJ:
        print(f"[playbook] core pooled, {k:8s}: {cp['recommendation'][k]}")
        counts = pd.Series([cp["table"][s][k]["status"] for s in cp["table"]]).value_counts().to_dict()
        print(f"[playbook]      statuses {counts}")
    mp = out["menu_pooled"]
    print(f"[playbook] menu: {mp['settings']} settings, {mp['settings_supported']} with at least {MIN_CELLS} cells")
    for k in OBJ:
        print(f"[playbook] menu pooled, {k:8s}: {mp['recommendation'][k]}")
    per = {}
    for ctx, v in out["core_by_context"].items():
        for k in OBJ:
            per.setdefault(k, []).append(v["recommendation"][k]["entry"])
    for k in OBJ:
        print(f"[playbook] core by context, {k:8s}: {pd.Series(per[k]).value_counts().to_dict()}")
    for k, v in out["envelope_sensitivity"].items():
        print(f"[playbook] envelope {k:14s} admits {v['admitted_core_settings']} core settings; changed {v['changed_from_published']}")
    path = Path(out_path) if out_path else Path(root) / "core" / "playbook.json"
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(strip(out), indent=1, default=float))
    print(f"[playbook] wrote {path}")
    return 0


def selftest():
    rng = np.random.default_rng(0)
    rows = []
    settings = {"base": dict(BASE, a_temperature=0.7, a_mc_dropout=0.0, a_cfg_scale=1.0),
                "better": dict(BASE, a_clamp=0.03, a_temperature=0.7, a_mc_dropout=0.0, a_cfg_scale=1.0),
                "same": dict(BASE, a_clamp=0.01, a_temperature=0.7, a_mc_dropout=0.0, a_cfg_scale=1.0),
                "toxic": dict(BASE, a_clamp=0.05, a_temperature=0.7, a_mc_dropout=0.0, a_cfg_scale=1.0)}
    for name, lv in settings.items():
        for c in range(4):
            for sd in range(40):
                u = 0.6 + (0.2 if name == "better" else 0.0) + rng.normal(0, 0.05)
                tox = 0.4 if name == "toxic" else 0.05
                rows.append(dict(lv, tier="core", s_pool_imbalance=c, s_bad_actor_frac=0.1, seed=sd, r_util=u,
                                 r_safe=1 - tox + rng.normal(0, 0.01), r_fid=-0.3, r_indiv=(np.nan if sd < 5 else 0.5 + (0.2 if name == "better" else 0.0) + rng.normal(0, 0.05)), r_fair=0.0, r_sys=np.nan,
                                 r_read=0.95, text_health="HEALTHY", canary_caught=1.0))
    thin = dict(BASE, a_clamp=0.04, a_temperature=0.7, a_mc_dropout=0.0, a_cfg_scale=1.0)
    for sd in range(10):
        rows.append(dict(thin, tier="core", s_pool_imbalance=0, s_bad_actor_frac=0.1, seed=sd, r_util=0.9, r_safe=0.95,
                         r_fid=-0.3, r_indiv=0.5, r_fair=0.0, r_sys=-1.0, r_read=0.95, text_health="HEALTHY", canary_caught=1.0))
    global NB
    NB = 300
    df = prep(pd.DataFrame(rows))
    base = df[is_base(df)]["setting"].iloc[0]
    cmp = compare(df, base, [s for s in df["setting"].unique() if s != base], np.random.default_rng(1))
    table, rec, _ = statuses(cmp)
    key = {n: prep(pd.DataFrame([dict(lv, tier="core", s_pool_imbalance=0, s_bad_actor_frac=0.1, seed=0, r_util=0, r_safe=1,
                                      r_fid=0, r_indiv=0, r_fair=0, r_sys=0, r_read=0, text_health="HEALTHY",
                                      canary_caught=1)]))["setting"].iloc[0] for n, lv in list(settings.items()) + [("thin", thin)]}
    ok = True

    def case(label, good):
        nonlocal ok
        ok &= bool(good)
        print(f"  {label} -> {'OK' if good else 'FAIL'}")
    case("PLANTED-PASS   a setting 0.2 better on utility reads BETTER THAN BASELINE", table[key["better"]]["r_util"]["status"] == "BETTER THAN BASELINE")
    case("PLANTED-FAIL 1 a setting equal to the baseline reads UNRESOLVED, never equal", table[key["same"]]["r_util"]["status"] == "UNRESOLVED")
    case("PLANTED-FAIL 2 a setting with 10 cells reads INSUFFICIENT SUPPORT", table[key["thin"]]["r_util"]["status"] == "INSUFFICIENT SUPPORT")
    case("PLANTED-FAIL 3 a setting whose kept posts are toxic reads OUTSIDE THE LIMITS", table[key["toxic"]]["r_util"]["status"] == "OUTSIDE THE LIMITS")
    case("PLANTED-PASS   utility's recommendation is the better setting", rec["r_util"].get("setting") == key["better"])
    case("PLANTED-FAIL 4 an objective no setting improves reads INSUFFICIENT EVIDENCE", rec["r_fair"]["entry"].startswith("INSUFFICIENT EVIDENCE"))
    case("PLANTED-PASS   individuation 0.2 better, undefined on 5 of 40 seeds, reads BETTER on the blocks both carry", table[key["better"]]["r_indiv"]["status"] == "BETTER THAN BASELINE" and cmp[key["better"]]["blocks_compared"]["r_indiv"] == 140)
    case("PLANTED-FAIL 5 an objective undefined in every cell reads UNDEFINED, never UNRESOLVED or INSUFFICIENT EVIDENCE", table[key["same"]]["r_sys"]["status"] == "UNDEFINED" and rec["r_sys"]["entry"].startswith("UNDEFINED"))
    print("\n  SELFTEST PASSED" if ok else "\n  SELFTEST FAILED")
    return 0 if ok else 1


if __name__ == "__main__":
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("--selftest", action="store_true")
    ap.add_argument("--root", default=".", help="the corpus root, the directory holding the tiers; in the release that "
                                                "is the release directory itself")
    ap.add_argument("--out", default="", help="where to write the readout (default: core/playbook.json under --root)")
    a = ap.parse_args()
    sys.exit(selftest() if a.selftest else main(a.root, a.out))