Datasets:
Tasks:
Reinforcement Learning
Formats:
parquet
Size:
100M - 1B
Tags:
offline-reinforcement-learning
off-policy-evaluation
contextual-bandit
content-moderation
benchmark
License:
Download code/ds4_task2_core.py from thwalsh/moderators-playbook-benchmark: direct link, hf CLI and curl.
- Browser
- Download file 23.1 kB
-
https://huggingface.co/datasets/thwalsh/moderators-playbook-benchmark/resolve/main/code/ds4_task2_core.py
- Command line
-
hf download hf://datasets/thwalsh/moderators-playbook-benchmark/code/ds4_task2_core.py
-
curl -L -o ds4_task2_core.py https://huggingface.co/datasets/thwalsh/moderators-playbook-benchmark/resolve/main/code/ds4_task2_core.py
23.1 kB
| #!/usr/bin/env python | |
| """Task 2 on the core, specified and scored, with the core-only tension and Pareto uncertainty (RQ4 ledger 9.62as). | |
| WHY. The 2026-10-15 cold read of dataset 4 found Task 2 unspecified (D5): no score, no reference point, no list of | |
| objectives, no baseline, no evaluator, and an envelope that never binds where outcomes are known. It found the H3 | |
| tension evidence pooled across contexts, seeds and tiers with no uncertainty (D7), and it could not reconcile the | |
| learning gains with Task 1 (D10). This file answers all three from the core's full grid and the five tier traces. | |
| THE TASK. A submission is one core setting per context: 12 integers, each 0 to 19, in the order of `contexts`. It is | |
| scored on the EVALUATION seeds, a fixed half of the 50 chosen by seed 142 and listed in the output, from the full | |
| grid, so every chosen setting has its outcome in every context. The other 25 are the SELECTION seeds a submission may | |
| learn from. | |
| violation rate the share of the 12 contexts whose chosen setting breaches the safety envelope on the evaluation | |
| seeds: toxicity of kept posts above 0.15, readable share below 0.5, or canary catch below 0.5 (the | |
| envelope `menu.json` applies to the whole corpus) | |
| value the mean over contexts of r_util + r_safe + |r_fid|, Task 1's graded composite | |
| hypervolume the volume the policy's point dominates in (r_util, r_safe, |r_fid|), each objective scaled to | |
| [0, 1] by the smallest and largest of the 20 settings' evaluation-seed means, which are published | |
| Each carries a 95 percent interval from a bootstrap of the evaluation seeds, and baselines are compared paired. | |
| BASELINES, chosen on the selection seeds alone: | |
| uniform every setting equally, an expectation | |
| random acceptable per context, a setting drawn uniformly from those acceptable there, an expectation | |
| best fixed the one setting acceptable in every context with the highest pooled value | |
| per-context greedy per context, the acceptable setting with the highest value | |
| and the per-context oracle, chosen on the evaluation seeds themselves: in-sample and optimistic, never a baseline. | |
| THE ENVELOPE'S REACH on the core, counted on all 50 seeds and on each half. | |
| ROBUSTNESS: greedy minus best fixed over 200 random 25/25 splits. | |
| D7: the safety and fairness correlation across the 20 settings, within each context, and within each forum draw, | |
| each with a seed-cluster bootstrap; and the probability that each corpus setting with 30 or more cells is | |
| non-dominated, by a bootstrap of its cells, on six, five (without r_sys) and four (without r_sys and r_indiv) | |
| objectives. | |
| D10: Task 1's target arm is the pooled best on r_total, the signed sum; its value on the graded composite is read | |
| beside the composite's own pooled best, which is what the reviewer's arithmetic assumed it was. | |
| python scripts/ds4_task2_core.py | |
| python scripts/ds4_task2_core.py --selftest | |
| """ | |
| import argparse | |
| import json | |
| import os | |
| import sys | |
| import tempfile | |
| import warnings | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| ROOT = "/sciclone/data10/thwalsh/hypernets/results/rq4_g1r" | |
| # the menu's four tiers (18,800 forums, 243 settings); the controls tier is a factorial, not a menu (ds4_mpb_menu.py) | |
| TIERS = ("core", "periphery", "stress", "decode") | |
| OBJ3 = ("r_util", "r_safe", "abs_fid") | |
| MENU_OBJ = ("r_util", "r_safe", "r_fid_mag", "r_indiv", "r_fair", "r_sys") | |
| MENU_LEVERS = ("a_delta_scale", "a_clamp", "a_rank", "a_arditi_alpha", "a_temperature", "a_mc_dropout", "a_cfg_scale") | |
| SEED = 142 | |
| # THE PUBLISHED ENVELOPE, the definition of Task 2's constraint. A menu.json under --root must carry the same one. | |
| ENVELOPE = {"tox_floor": 0.15, "min_coh": 0.5, "min_canary": 0.5} | |
| def core_tensors(df): | |
| """(context, seed, setting) tensors for every quantity Task 2 reads. Refuses a grid with a hole.""" | |
| df = df.copy() | |
| df["_ctx"] = df["s_pool_imbalance"].astype(str) + "|" + df["s_bad_actor_frac"].astype(str) | |
| ctxs, seeds, arms = sorted(df["_ctx"].unique()), sorted(df["seed"].unique()), sorted(df["config_idx"].unique()) | |
| if len(df) != len(ctxs) * len(seeds) * len(arms) or df.duplicated(["_ctx", "seed", "config_idx"]).any(): | |
| raise ValueError(f"the core is not a full grid: {len(df)} rows for {len(ctxs)} x {len(seeds)} x {len(arms)}") | |
| df = df.sort_values(["_ctx", "seed", "config_idx"]) | |
| shp = (len(ctxs), len(seeds), len(arms)) | |
| q = {"r_util": df["r_util"], "r_safe": df["r_safe"], "abs_fid": df["r_fid"].abs(), "r_fair": df["r_fair"], | |
| "readable": df["text_health"].isin(["HEALTHY", "MARGINAL"]).astype(float), | |
| "canary": df["canary_caught"].astype(float)} | |
| T = {k: v.to_numpy(float).reshape(shp) for k, v in q.items()} | |
| bad = [k for k, v in T.items() if not np.isfinite(v).all()] | |
| if bad: | |
| raise ValueError(f"non-finite values in {bad}: Task 2 needs every outcome") | |
| T["composite"] = T["r_util"] + T["r_safe"] + T["abs_fid"] | |
| return T, ctxs, seeds, arms | |
| def means(T, idx): | |
| return {k: v[:, idx, :].mean(axis=1) for k, v in T.items()} | |
| def acceptable(M, env): | |
| return ((1.0 - M["r_safe"]) <= env["tox_floor"]) & (M["readable"] >= env["min_coh"]) & (M["canary"] >= env["min_canary"]) | |
| def baselines(T, sel, env): | |
| """Every baseline's weights, (context, setting), from the selection seeds alone.""" | |
| M = means(T, sel) | |
| ok = acceptable(M, env) | |
| n_ctx, n_arm = ok.shape | |
| if not ok.any(axis=1).all(): | |
| raise ValueError("a context has no acceptable setting on the selection seeds; the task is undefined there") | |
| W = {"uniform": np.full((n_ctx, n_arm), 1.0 / n_arm), | |
| "random acceptable": ok / ok.sum(axis=1, keepdims=True)} | |
| every = ok.all(axis=0) | |
| if not every.any(): | |
| raise ValueError("no setting is acceptable in every context on the selection seeds") | |
| pooled = np.where(every, M["composite"].mean(axis=0), -np.inf) | |
| W["best fixed"] = np.zeros((n_ctx, n_arm)); W["best fixed"][:, int(np.argmax(pooled))] = 1.0 | |
| g = np.where(ok, M["composite"], -np.inf).argmax(axis=1) | |
| W["per-context greedy"] = np.zeros((n_ctx, n_arm)); W["per-context greedy"][np.arange(n_ctx), g] = 1.0 | |
| return W | |
| def oracle(M, env): | |
| ok = acceptable(M, env) | |
| g = np.where(ok, M["composite"], -np.inf).argmax(axis=1) | |
| W = np.zeros(ok.shape); W[np.arange(ok.shape[0]), g] = 1.0 | |
| return W | |
| def score(M, W, env, scale): | |
| ok = acceptable(M, env) | |
| pt = np.array([(W * M[o]).sum(axis=1).mean() for o in OBJ3]) | |
| z = np.clip((pt - scale["lo"]) / (scale["hi"] - scale["lo"]), 0.0, None) | |
| return {"violation": float((W * ~ok).sum(axis=1).mean()), "value": float((W * M["composite"]).sum(axis=1).mean()), | |
| "hypervolume": float(np.prod(z)), **{o: float(v) for o, v in zip(OBJ3, pt)}} | |
| def _ci(x): | |
| return [float(np.percentile(x, 2.5)), float(np.percentile(x, 97.5))] | |
| def task2(T, env, B=2000, splits=200, seed=SEED): | |
| n_ctx, n_seed, n_arm = T["composite"].shape | |
| perm = np.random.RandomState(seed).permutation(n_seed) | |
| sel, ev = np.sort(perm[: n_seed // 2]), np.sort(perm[n_seed // 2:]) | |
| W = baselines(T, sel, env) | |
| Mev = means(T, ev) | |
| arm_pts = np.array([[Mev[o].mean(axis=0)[a] for o in OBJ3] for a in range(n_arm)]) | |
| scale = {"lo": arm_pts.min(axis=0), "hi": arm_pts.max(axis=0)} | |
| if np.any(scale["hi"] <= scale["lo"]): | |
| raise ValueError("an objective is constant across the settings; the hypervolume scale is undefined") | |
| out = {k: score(Mev, w, env, scale) for k, w in W.items()} | |
| out["per-context oracle"] = score(Mev, oracle(Mev, env), env, scale) | |
| rng = np.random.RandomState(seed + 3) | |
| draws = {k: {m: [] for m in ("violation", "value", "hypervolume")} for k in out} | |
| pairs = {p: [] for p in ("per-context greedy - best fixed", "best fixed - uniform", "per-context greedy - uniform", | |
| "per-context oracle - per-context greedy", "best fixed - random acceptable")} | |
| for _ in range(B): | |
| idx = ev[rng.randint(0, len(ev), len(ev))] | |
| Mb = means(T, idx) | |
| sc = {k: score(Mb, w, env, scale) for k, w in W.items()} | |
| sc["per-context oracle"] = score(Mb, oracle(Mb, env), env, scale) | |
| for k, s in sc.items(): | |
| for m in draws[k]: | |
| draws[k][m].append(s[m]) | |
| for p in pairs: | |
| a, b = p.split(" - ") | |
| pairs[p].append(sc[a]["value"] - sc[b]["value"]) | |
| for k in out: | |
| for m in ("violation", "value", "hypervolume"): | |
| out[k][f"{m}_ci95"] = _ci(draws[k][m]) | |
| paired = {p: {"mean": float(np.mean(v)), "ci95": _ci(v), "point": out[p.split(" - ")[0]]["value"] | |
| - out[p.split(" - ")[1]]["value"]} for p, v in pairs.items()} | |
| # the envelope's reach on the core | |
| reach = {} | |
| for name, idx in (("all 50 seeds", np.arange(n_seed)), ("selection seeds", sel), ("evaluation seeds", ev)): | |
| M = means(T, idx) | |
| ok = acceptable(M, env) | |
| reach[name] = {"pairs_breaching": int((~ok).sum()), "pairs": int(ok.size), | |
| "contexts_with_a_breach": int((~ok).any(axis=1).sum()), | |
| "by_constraint": {"toxicity": int(((1 - M["r_safe"]) > env["tox_floor"]).sum()), | |
| "readable": int((M["readable"] < env["min_coh"]).sum()), | |
| "canary": int((M["canary"] < env["min_canary"]).sum())}} | |
| # robustness over random splits | |
| rs = np.random.RandomState(seed + 5) | |
| gf, fu, gv = [], [], [] | |
| for _ in range(splits): | |
| p_ = rs.permutation(n_seed) | |
| s_, e_ = p_[: n_seed // 2], p_[n_seed // 2:] | |
| try: | |
| W_ = baselines(T, s_, env) | |
| except ValueError: | |
| continue | |
| M_ = means(T, e_) | |
| v = {k: score(M_, w, env, scale)["value"] for k, w in W_.items()} | |
| gf.append(v["per-context greedy"] - v["best fixed"]); fu.append(v["best fixed"] - v["uniform"]) | |
| gv.append(score(M_, W_["per-context greedy"], env, scale)["violation"]) | |
| choice = {k: [int(np.argmax(w[c])) for c in range(n_ctx)] for k, w in W.items() if k in ("best fixed", "per-context greedy")} | |
| return {"selection_seeds": [int(x) for x in sel], "evaluation_seeds": [int(x) for x in ev], | |
| "scale": {"objectives": list(OBJ3), "lo": scale["lo"].tolist(), "hi": scale["hi"].tolist()}, | |
| "policies": out, "paired_value": paired, "choices": choice, "envelope_reach": reach, | |
| "splits": {"n": len(gf), "greedy_minus_fixed": {"mean": float(np.mean(gf)), "range95": _ci(gf), | |
| "share_positive": float(np.mean(np.array(gf) > 0))}, | |
| "fixed_minus_uniform": {"mean": float(np.mean(fu)), "range95": _ci(fu)}, | |
| "greedy_violation": {"mean": float(np.mean(gv)), "max": float(np.max(gv))}}} | |
| def _corr(x, y): | |
| x, y = x - x.mean(), y - y.mean() | |
| d = np.sqrt((x * x).sum() * (y * y).sum()) | |
| return float((x * y).sum() / d) if d > 0 else float("nan") | |
| def tension(T, B=2000, seed=SEED): | |
| """r_safe against r_fair on the core: across the 20 settings, within each context, within each forum draw.""" | |
| n_ctx, n_seed, n_arm = T["r_safe"].shape | |
| def stats(idx): | |
| S, F = T["r_safe"][:, idx, :], T["r_fair"][:, idx, :] | |
| arm = _corr(S.mean(axis=(0, 1)), F.mean(axis=(0, 1))) | |
| within = [_corr(S[c].mean(axis=0), F[c].mean(axis=0)) for c in range(n_ctx)] | |
| wz = float(np.tanh(np.nanmean(np.arctanh(np.clip(within, -0.999999, 0.999999))))) | |
| Sd = S - S.mean(axis=2, keepdims=True) | |
| Fd = F - F.mean(axis=2, keepdims=True) | |
| draw = _corr(Sd.ravel(), Fd.ravel()) | |
| cell = _corr(S.ravel(), F.ravel()) | |
| return arm, wz, draw, cell, within | |
| a0, w0, d0, c0, within0 = stats(np.arange(n_seed)) | |
| rng = np.random.RandomState(seed + 9) | |
| bs = np.array([stats(rng.randint(0, n_seed, n_seed))[:4] for _ in range(B)]) | |
| # The INTERVAL is the seed jackknife's. A bootstrap draw repeats seeds, which adds noise to every setting mean and | |
| # pulls a correlation of means toward zero, so its percentile interval can sit beside the estimate instead of | |
| # around it (it did for the within-context mean). The bootstrap still gives the share of draws below zero. | |
| jk = np.array([stats(np.delete(np.arange(n_seed), i))[:4] for i in range(n_seed)]) | |
| se = np.sqrt((n_seed - 1) / n_seed * ((jk - jk.mean(axis=0)) ** 2).sum(axis=0)) | |
| names = ("across the 20 settings", "within context, mean of 12", "within forum draw", "cells, pooled") | |
| return {n: {"r": float(v), "ci95": [float(v - 1.96 * se[i]), float(v + 1.96 * se[i])], "jackknife_se": float(se[i]), | |
| "boot_range95": _ci(bs[:, i]), "share_negative": float(np.mean(bs[:, i] < 0))} | |
| for i, (n, v) in enumerate(zip(names, (a0, w0, d0, c0)))} | { | |
| "within_context_each": [float(x) for x in within0], "contexts_negative": int(np.sum(np.array(within0) < 0))} | |
| def pareto_mask(M): | |
| X = np.where(np.isfinite(M), M, -np.inf) | |
| n = len(X) | |
| nd = np.ones(n, bool) | |
| for i in range(n): | |
| dom = np.all(X >= X[i], axis=1) & np.any(X > X[i], axis=1) | |
| nd[i] = not dom.any() | |
| return nd | |
| def pareto_uncertainty(df, min_cells=30, B=1000, seed=SEED): | |
| df = df.copy() | |
| df["r_fid_mag"] = df["r_fid"] | |
| df["arm_key"] = df[list(MENU_LEVERS)].astype(str).agg("|".join, axis=1) | |
| g = df.groupby("arm_key") | |
| n = g.size() | |
| keep = n[n >= min_cells].index | |
| sub = df[df["arm_key"].isin(keep)] | |
| groups = [grp[list(MENU_OBJ)].to_numpy(float) for _, grp in sub.groupby("arm_key")] | |
| keys = [k for k, _ in sub.groupby("arm_key")] | |
| def arm_means(rows): | |
| with warnings.catch_warnings(): | |
| warnings.simplefilter("ignore", category=RuntimeWarning) # an all-NaN column is NaN, ranked worst | |
| m = np.array([np.nanmean(r, axis=0) for r in rows]) | |
| m[:, MENU_OBJ.index("r_fid_mag")] = np.abs(m[:, MENU_OBJ.index("r_fid_mag")]) | |
| return m | |
| sets = {"six objectives": list(range(6)), "five, without r_sys": [0, 1, 2, 3, 4], | |
| "four, without r_sys and r_indiv": [0, 1, 2, 4]} | |
| point = arm_means(groups) | |
| rng = np.random.RandomState(seed + 17) | |
| hits = {s: np.zeros(len(groups)) for s in sets} | |
| for _ in range(B): | |
| bm = arm_means([r[rng.randint(0, len(r), len(r))] for r in groups]) | |
| for s, cols in sets.items(): | |
| hits[s] += pareto_mask(bm[:, cols]) | |
| out = {"min_cells": min_cells, "settings": len(groups), "boot": B, "sets": {}} | |
| for s, cols in sets.items(): | |
| p = hits[s] / B | |
| nd = pareto_mask(point[:, cols]) | |
| out["sets"][s] = {"non_dominated_point": int(nd.sum()), "expected_non_dominated": float(p.sum()), | |
| "p_at_least_0.95": int((p >= 0.95).sum()), "p_at_least_0.5": int((p >= 0.5).sum()), | |
| "p_below_0.05": int((p < 0.05).sum())} | |
| out["all_settings_rankable"] = int((n >= 4).sum()) | |
| out["keys"] = keys | |
| return out | |
| def task1_target(core): | |
| """Task 1's targets mix toward the pooled best arm on r_total (signed). Read its composite value beside the | |
| composite's own pooled best and the uniform policy, on all 50 seeds.""" | |
| c = core.copy() | |
| c["comp"] = c["r_util"] + c["r_safe"] + c["r_fid"].abs() | |
| by = c.groupby("config_idx") | |
| a_tot, a_comp = int(by["r_total"].mean().idxmax()), int(by["comp"].mean().idxmax()) | |
| u = float(c["comp"].mean()) | |
| return {"pooled_best_on_r_total": a_tot, "pooled_best_on_composite": a_comp, | |
| "composite_uniform": u, "composite_of_r_total_best": float(by["comp"].mean()[a_tot]), | |
| "composite_of_composite_best": float(by["comp"].mean()[a_comp]), | |
| "gain_r_total_best_over_uniform": float(by["comp"].mean()[a_tot] - u), | |
| "gain_composite_best_over_uniform": float(by["comp"].mean()[a_comp] - u)} | |
| def load(root): | |
| core = pd.read_parquet(os.path.join(root, "core", "trace.parquet")) | |
| frames = [] | |
| for t in TIERS: | |
| f = os.path.join(root, t, "trace.parquet") | |
| if not os.path.isfile(f): | |
| raise SystemExit(f"[task2] FATAL: {f} is missing; the Pareto reading covers the menu's four tiers") | |
| d = pd.read_parquet(f); d["tier"] = t; frames.append(d) | |
| return core, pd.concat(frames, ignore_index=True) | |
| def run(root, out, B=2000, splits=200, pboot=1000): | |
| mp = os.path.join(root, "menu.json") | |
| env = dict(ENVELOPE) | |
| if os.path.isfile(mp): | |
| menv = {k: float(json.load(open(mp))["envelope"][k]) for k in ENVELOPE} | |
| if menv != ENVELOPE: | |
| raise SystemExit(f"[task2] FATAL: {mp} was built with the envelope {menv}, not the published {ENVELOPE}; " | |
| f"Task 2's constraint is the published one") | |
| core, allt = load(root) | |
| T, ctxs, seeds, arms = core_tensors(core) | |
| res = {"protocol": __doc__.split("THE TASK.")[1].split("BASELINES")[0].strip(), "root": root, | |
| "envelope": env, "envelope_source": "the published envelope" + (", matched by menu.json" | |
| if os.path.isfile(mp) else ""), | |
| "contexts": ctxs, "arms": [int(a) for a in arms], "n_seeds": len(seeds)} | |
| res["task2"] = task2(T, env, B=B, splits=splits) | |
| res["tension"] = tension(T, B=B) | |
| res["pareto"] = pareto_uncertainty(allt, B=pboot) | |
| res["task1_target"] = task1_target(core) | |
| Path(out).write_text(json.dumps(res, indent=1)) | |
| t2 = res["task2"] | |
| for k, s in t2["policies"].items(): | |
| print(f"[task2] {k:<20} violation {s['violation']:.3f} {s['violation_ci95']} value {s['value']:.4f} " | |
| f"[{s['value_ci95'][0]:.4f}, {s['value_ci95'][1]:.4f}] hypervolume {s['hypervolume']:.3f}") | |
| for p, v in t2["paired_value"].items(): | |
| print(f"[task2] {p:<40} {v['point']:+.4f} bootstrap [{v['ci95'][0]:+.4f}, {v['ci95'][1]:+.4f}]") | |
| print(f"[task2] envelope reach: {json.dumps(t2['envelope_reach'])}") | |
| print(f"[task2] splits: {json.dumps(t2['splits'])}") | |
| print(f"[task2] choices: {t2['choices']}") | |
| for n, v in res["tension"].items(): | |
| if isinstance(v, dict): | |
| print(f"[tension] {n:<28} r {v['r']:+.3f} [{v['ci95'][0]:+.3f}, {v['ci95'][1]:+.3f}] negative in " | |
| f"{100 * v['share_negative']:.1f}% of draws") | |
| print(f"[tension] contexts with a negative within-context r: {res['tension']['contexts_negative']} of {len(ctxs)}") | |
| print(f"[pareto] {json.dumps({k: v for k, v in res['pareto'].items() if k != 'keys'})}") | |
| print(f"[task1] {json.dumps(res['task1_target'])}") | |
| print(f"[task2] wrote {out}") | |
| return res | |
| def _fixture(td, signal=True): | |
| rng = np.random.RandomState(4) | |
| rows = [] | |
| for c in range(4): | |
| for s in range(20): | |
| for a in range(6): | |
| best = 2 if c < 2 else 4 | |
| u = 0.5 + (0.2 if (signal and a == best) else 0.0) + rng.normal(0, 0.02) | |
| rows.append({"s_pool_imbalance": float(c), "s_bad_actor_frac": 0.1, "seed": s, "config_idx": a, | |
| "r_util": u, "r_safe": (0.95 if not (signal and a == 5 and c == 0) else 0.80) | |
| + (0.0 if signal else rng.normal(0, 0.005)), | |
| "r_fid": -0.1 - (0.01 * a if signal else rng.normal(0, 0.005)), | |
| "r_fair": -0.05 - 0.002 * a + rng.normal(0, 0.005), "r_total": u, | |
| "text_health": "HEALTHY", "canary_caught": 1.0, "r_indiv": 0.3, "r_sys": -1.0, | |
| "a_delta_scale": 1.0, "a_clamp": 0.0025, "a_rank": 24.0, "a_arditi_alpha": float(a), | |
| "a_temperature": 0.7, "a_mc_dropout": 0.0, "a_cfg_scale": 1.0}) | |
| return pd.DataFrame(rows) | |
| def selftest(): | |
| ok = True | |
| env = {"tox_floor": 0.15, "min_coh": 0.5, "min_canary": 0.5} | |
| T, *_ = core_tensors(_fixture(None)) | |
| r = task2(T, env, B=200, splits=40) | |
| pol = r["policies"] | |
| good = (r["choices"]["per-context greedy"] == [2, 2, 4, 4] | |
| and r["paired_value"]["per-context greedy - best fixed"]["ci95"][0] > 0 | |
| and r["envelope_reach"]["all 50 seeds"]["pairs_breaching"] == 1 | |
| and r["envelope_reach"]["all 50 seeds"]["by_constraint"]["toxicity"] == 1 | |
| and pol["random acceptable"]["violation"] == 0.0 and abs(pol["uniform"]["violation"] - 1 / 24) < 1e-12) | |
| print(f" PLANTED-PASS a contextual best (2, 2, 4, 4) is found by the greedy baseline, beats the best fixed " | |
| f"setting with its interval clear of zero, and the one breaching pair is counted -> {'OK' if good else 'FAIL'}") | |
| ok &= good | |
| T0, *_ = core_tensors(_fixture(None, signal=False)) | |
| r0 = task2(T0, env, B=200, splits=40) | |
| lo, hi = r0["paired_value"]["per-context greedy - best fixed"]["ci95"] | |
| good = lo < 0.01 and r0["splits"]["greedy_minus_fixed"]["mean"] < 0.01 | |
| print(f" PLANTED-FAIL 1 on pure noise the greedy baseline gains nothing over the best fixed setting " | |
| f"({r0['splits']['greedy_minus_fixed']['mean']:+.4f}) -> {'OK' if good else 'FAIL'}") | |
| ok &= good | |
| holed = _fixture(None).iloc[1:] | |
| try: | |
| core_tensors(holed) | |
| print(" PLANTED-FAIL 2 a core with a missing cell was NOT refused -> FAIL"); ok = False | |
| except ValueError: | |
| print(" PLANTED-FAIL 2 a core with a missing cell is refused -> OK") | |
| strict = {"tox_floor": 0.01, "min_coh": 0.5, "min_canary": 0.5} | |
| try: | |
| baselines(T, np.arange(10), strict) | |
| print(" PLANTED-FAIL 3 an envelope no setting meets was NOT refused -> FAIL"); ok = False | |
| except ValueError: | |
| print(" PLANTED-FAIL 3 an envelope no setting meets is refused, never scored as zero -> OK") | |
| nan_df = _fixture(None); nan_df.loc[0, "r_safe"] = np.nan | |
| try: | |
| core_tensors(nan_df) | |
| print(" PLANTED-FAIL 4 a missing outcome was NOT refused -> FAIL"); ok = False | |
| except ValueError: | |
| print(" PLANTED-FAIL 4 a non-finite outcome is refused -> OK") | |
| M = np.array([[1, 1], [0, 0], [1, 0], [0.5, 2]], float) | |
| good = pareto_mask(M).tolist() == [True, False, False, True] | |
| print(f" PLANTED-PASS the Pareto mask keeps exactly the two non-dominated rows -> {'OK' if good else 'FAIL'}") | |
| ok &= good | |
| print("\n SELFTEST PASSED" if ok else "\n SELFTEST FAILED") | |
| return 0 if ok else 1 | |
| def main(): | |
| ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) | |
| ap.add_argument("--root", default=ROOT) | |
| ap.add_argument("--out", default="") | |
| ap.add_argument("--boot", type=int, default=2000) | |
| ap.add_argument("--splits", type=int, default=200) | |
| ap.add_argument("--pareto_boot", type=int, default=1000) | |
| ap.add_argument("--selftest", action="store_true") | |
| a = ap.parse_args() | |
| if a.selftest: | |
| return selftest() | |
| run(a.root, a.out or os.path.join(a.root, "core", "task2_core.json"), B=a.boot, splits=a.splits, | |
| pboot=a.pareto_boot) | |
| return 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |