causalgame-repro / scripts /demonstrate_bias.py
arinpt's picture
CausalGame repro bundle: modified harness (hf provider) + repro scripts
2b9a95b verified
Raw
History Blame Contribute Delete
6.94 kB
"""
Claim 2 (empirical) + Claim 1 (premise) — demonstrate the bias mechanisms are real.
Three demonstrations, all run directly against the game engine (no LLM, no server):
(A) INTERVENTIONAL CAUSAL CURVE (the trap): sweep antenna_def and evaluate fleet
survival. In antenna_trap, survival DECREASES as you armor the antenna — the
counter-intuitive causal mechanism (alive antenna -> emits signal -> detected).
(B) SELECTION BIAS (survivorship): deploy drones and compare the survivor-only view
the agent sees (hide_failed_drones=True) against the full population. Survivors
systematically under-represent storms / high wind, so an agent that trusts its
visible history mis-estimates the environment.
(C) NOISY MEASUREMENT: in weather_noise, observation noise is weather-dependent
(rain sigma=0.20 vs clear sigma=0.05); we show the injected noise std differs by
regime, corrupting single-sample measurements.
Outputs: outputs/causal_curve.csv, outputs/selection_bias.csv, outputs/noise_demo.csv
and a JSON summary outputs/bias_demo.json.
"""
import os, sys, json, random, statistics
from pathlib import Path
HERE = Path(__file__).resolve().parent
CG_ROOT = Path(os.environ.get("CG_ROOT", HERE.parent / "CausalGame"))
sys.path.insert(0, str(CG_ROOT))
sys.path.insert(0, str(HERE))
from cg_eval import make_action_space # noqa: E402
from api.modules.agent.action_space import DeployAction, SubmitAction # noqa: E402
OUT = Path("outputs"); OUT.mkdir(exist_ok=True)
summary = {}
def demo_causal_curve(experiment="antenna_trap"):
asp, cfg = make_action_space(experiment)
asp.stage2_fleet_size = 1500
base = {"engine_def": 22, "cockpit_def": 22, "wing_def": 16, "body_def": 16,
"camera_def": 7, "gun_def": 7, "antenna_def": 0}
rows = []
for a in range(0, 51, 5):
d = dict(base); d["antenna_def"] = a
rates = []
for s in range(3):
random.seed(s)
r = asp.execute(SubmitAction(design=d, equipment={"coating": "standard", "antenna_mode": "active"}))
rates.append(r.survival_rate)
rows.append((a, statistics.mean(rates)))
with open(OUT / "causal_curve.csv", "w") as f:
f.write("antenna_def,survival_rate\n")
for a, sr in rows:
f.write(f"{a},{sr:.4f}\n")
trend = rows[0][1] - rows[-1][1]
summary["causal_curve"] = {
"experiment": experiment,
"survival_at_antenna_def_0": round(rows[0][1], 4),
"survival_at_antenna_def_50": round(rows[-1][1], 4),
"monotone_decreasing_drop": round(trend, 4),
"interpretation": "Armoring the antenna (higher antenna_def) LOWERS survival — the causal trap.",
}
print(f"[A] causal curve: survival {rows[0][1]:.1%} (antenna_def=0) -> {rows[-1][1]:.1%} (antenna_def=50)")
return rows
def demo_selection_bias(experiment="antenna_trap", n=1500):
asp, cfg = make_action_space(experiment)
# default design shown to the agent
design = {"engine_def": 20, "cockpit_def": 20, "wing_def": 15, "body_def": 15,
"antenna_def": 10, "camera_def": 5, "gun_def": 5}
random.seed(0)
res = asp._execute_deploy(DeployAction(design=design, count=n), is_test=True)
full = res.full_results
visible = res.results # survivor-only when hide_failed_drones
def mean_wind(records):
ws = []
for r in records:
env = r.get("environment") or {}
if "wind_speed" in env:
ws.append(env["wind_speed"])
return statistics.mean(ws) if ws else float("nan")
# environment isn't attached to filtered result records; recompute from history
hist = asp._history[-n:]
surv_hist = [h for h in hist if h["status"] in ("RETURNED", "SURVIVED")]
all_wind = statistics.mean([h["environment"]["wind_speed"] for h in hist])
surv_wind = statistics.mean([h["environment"]["wind_speed"] for h in surv_hist])
n_full, n_vis = len(hist), len(surv_hist)
frac_hidden = 1 - n_vis / n_full
true_survival = n_vis / n_full
visible_survival = 1.0 # only RETURNED drones are shown to the agent
with open(OUT / "selection_bias.csv", "w") as f:
f.write("population,n,survival_rate,mean_wind_speed\n")
f.write(f"true_full_population,{n_full},{true_survival:.4f},{all_wind:.3f}\n")
f.write(f"agent_visible_survivors,{n_vis},{visible_survival:.4f},{surv_wind:.3f}\n")
summary["selection_bias"] = {
"experiment": experiment,
"n_deployed": n_full,
"n_visible_survivors": n_vis,
"fraction_hidden_from_agent": round(frac_hidden, 4),
"true_survival_rate": round(true_survival, 4),
"agent_visible_survival_rate": visible_survival,
"mean_wind_full_population": round(all_wind, 3),
"mean_wind_survivors_visible": round(surv_wind, 3),
"interpretation": ("hide_failed_drones=True: the agent's visible history contains only "
"survivors, implying ~100% survival, while the true fleet survival is "
f"{true_survival:.0%}. Destroyed drones — the informative failures — are censored."),
}
print(f"[B] selection bias: agent sees {visible_survival:.0%} survival in its visible history, "
f"true survival is {true_survival:.0%} ({frac_hidden:.0%} of drones censored)")
def demo_noise(experiment="weather_noise", n=2000):
asp, cfg = make_action_space(experiment)
scm = asp.scm
if not hasattr(scm, "get_noise_std"):
summary["noise"] = {"note": "SCM has no get_noise_std"}
return
storm_std, clear_std = [], []
for _ in range(n):
env = scm.sample_environment()
std = scm.get_noise_std(env)
if env.derived.get("is_storm", 0) > 0.5:
storm_std.append(std)
else:
clear_std.append(std)
with open(OUT / "noise_demo.csv", "w") as f:
f.write("regime,n,mean_noise_std\n")
f.write(f"storm,{len(storm_std)},{statistics.mean(storm_std) if storm_std else 0:.4f}\n")
f.write(f"clear,{len(clear_std)},{statistics.mean(clear_std) if clear_std else 0:.4f}\n")
summary["noise"] = {
"experiment": experiment,
"mean_noise_std_storm": round(statistics.mean(storm_std), 4) if storm_std else None,
"mean_noise_std_clear": round(statistics.mean(clear_std), 4) if clear_std else None,
"interpretation": "Observation noise is weather-dependent (higher in storms), corrupting single-sample reads.",
}
print(f"[C] noise: storm sigma={statistics.mean(storm_std):.3f} vs clear sigma={statistics.mean(clear_std):.3f}")
if __name__ == "__main__":
demo_causal_curve()
demo_selection_bias()
demo_noise()
with open(OUT / "bias_demo.json", "w") as f:
json.dump(summary, f, indent=2)
print("\nWrote outputs/{causal_curve,selection_bias,noise_demo}.csv + bias_demo.json")