edumirror-repro-code / experiments /run_experiments.py
ygoldi's picture
Upload folder using huggingface_hub
2a58472 verified
Raw
History Blame Contribute Delete
28.7 kB
#!/usr/bin/env python3
# =============================================================================
# run_experiments.py
# -----------------------------------------------------------------------------
# Responsible for: The single entrypoint that runs every claim's experiment and
# writes results to an output directory as JSON + CSV.
# Role in project: Runs identically on a laptop (--stage smoke, mock backend)
# and on an HF GPU Job (real vLLM backend). One script, one
# code path, so the smoke test actually exercises the real thing.
# Assumptions: Reads backend config from EDUMIRROR_* env vars (see llm.py).
# Writes to --out. Never reads the network except via the LLM.
# =============================================================================
"""Experiment driver for the EduMirror reproduction.
Stages:
smoke -- tiny mock-backed run proving the pipeline end to end
claim2 -- kindergarten scalability at 5/15/30 agents (Table 1)
claim3 -- dual measurement: bullying dynamics + RSES construct validity
claim4 -- pairwise win-rate heatmap across scenarios (Figure 4)
claim5 -- election intervention strategies (Figure 7)
all -- claim2 + claim3 + claim4 + claim5
Every stage writes <out>/<stage>.json and appends a row-per-record CSV so the
logbook can attach both the raw traces and the tables.
"""
from __future__ import annotations
import argparse
import csv
import json
import random
import statistics
import sys
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from edumirror.agents import AGENT_REGISTRY
from edumirror.gm import run_episode
from edumirror.judgecheck import CORRUPTIONS, probe_absolute, probe_pairwise
from edumirror.llm import llm_from_env
from edumirror.measure import (
RATING_METRICS,
pairwise_compare,
rate_behaviour,
rate_competition,
survey_rses,
survey_svo,
win_rate,
)
from edumirror.needs import init_need_state_from_profile
from edumirror.scenarios import (
BULLYING_INTERVENTIONS,
ELECTION_INTERVENTIONS,
bullying_scenario,
class_task_scenario,
election_scenario,
kindergarten_scenario,
representative_scenarios,
study_group_scenario,
)
#: Methods compared, in the paper's Table 1 column order.
METHODS = ["EduMirror", "LLMob", "BabyAGI", "D2A", "ReAct"]
#: Corruption names, for filtering probe output when logging.
CORRUPTION_KEYS = set(CORRUPTIONS)
def log(msg: str) -> None:
"""Print a timestamped progress line, flushed for live HF Job logs."""
print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)
def write_json(path: Path, obj) -> None:
"""Write `obj` as indented JSON, creating parent directories."""
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(obj, indent=2, default=str))
def write_csv(path: Path, rows: list[dict]) -> None:
"""Write a list of flat dicts as CSV (no-op when empty)."""
if not rows:
return
path.parent.mkdir(parents=True, exist_ok=True)
keys = list(rows[0])
with path.open("w", newline="") as fh:
writer = csv.DictWriter(fh, fieldnames=keys)
writer.writeheader()
writer.writerows(rows)
# -----------------------------------------------------------------------------
# Claim 2: kindergarten scalability (Table 1).
# -----------------------------------------------------------------------------
def stage_claim2(out: Path, args) -> dict:
"""
Run the kindergarten scalability experiment across group sizes and methods.
Args:
out: Output directory.
args: Parsed CLI args (group_sizes, n_steps, n_seeds, concurrency).
Returns:
A results dict: {"table": {size: {method: avg}}, "records": [...]}.
Why this design:
Every (size, method, seed) cell runs the SAME scenario object and the
SAME seed, so the only difference across methods is architecture. We run
n_seeds independent episodes per cell and report the mean, because a
single LLM episode is high-variance and a one-shot comparison would be
indistinguishable from noise. The paper does not state its own n, so we
report ours explicitly rather than matching an unknown.
"""
agent_llm = llm_from_env("agent")
judge = llm_from_env("judge")
records: list[dict] = []
for size in args.group_sizes:
scenario = kindergarten_scenario(n_agents=size, n_steps=args.n_steps)
for method in METHODS:
for seed in range(args.n_seeds):
t0 = time.time()
log(f"claim2: size={size} method={method} seed={seed} ...")
try:
ep = run_episode(
scenario, method, agent_llm, seed=seed, concurrency=args.concurrency
)
except Exception as exc: # noqa: BLE001
# One failed episode must not lose the other 44 cells.
log(f" EPISODE FAILED: {exc}")
records.append(
{"size": size, "method": method, "seed": seed, "error": str(exc)}
)
continue
rating = rate_behaviour(judge, ep.behaviour_text(), scenario.setting)
row = {
"size": size,
"method": method,
"seed": seed,
"elapsed_s": round(time.time() - t0, 1),
**{m: rating.scores.get(m) for m in RATING_METRICS},
"average": rating.average(list(RATING_METRICS)),
"rationale": rating.rationale,
}
records.append(row)
log(f" -> avg={row['average']} ({row['elapsed_s']}s)")
ep.save(out / "episodes" / f"kindergarten_{size}_{method}_{seed}.json")
# Aggregate to the Table 1 shape: mean of the per-seed averages.
table: dict[str, dict[str, float]] = {}
for size in args.group_sizes:
table[str(size)] = {}
for method in METHODS:
vals = [
r["average"]
for r in records
if r.get("size") == size
and r.get("method") == method
and isinstance(r.get("average"), (int, float))
]
table[str(size)][method] = round(statistics.mean(vals), 3) if vals else None
results = {"table": table, "records": records, "n_seeds": args.n_seeds,
"n_steps": args.n_steps}
write_json(out / "claim2.json", results)
write_csv(out / "claim2_records.csv", [r for r in records if "error" not in r])
log(f"claim2 table: {json.dumps(table)}")
return results
# -----------------------------------------------------------------------------
# Claim 3: dual measurement protocol.
# -----------------------------------------------------------------------------
def stage_claim3(out: Path, args) -> dict:
"""
Run the bullying case study with dual-track measurement + RSES validity check.
Args:
out: Output directory.
args: Parsed CLI args.
Returns:
Results dict with per-arm need dynamics, RSES pre/post, and the
internal-vs-external correlation.
Why the pre/post RSES design:
Appendix F.5 administers the RSES to Alice before and after the bullying
incidents and compares delta-RSES (external instrument) against
delta-Value on the "self worth"/"sense of respect" dimensions (internal
state). Agreement between them is the construct-validity evidence for
Claim 3: it shows the internal value numbers mean what they claim to.
We reproduce exactly that comparison.
"""
agent_llm = llm_from_env("agent")
surveyor = llm_from_env("judge")
records: list[dict] = []
for arm in BULLYING_INTERVENTIONS:
for seed in range(args.n_seeds):
scenario = bullying_scenario(arm, n_steps=args.n_steps)
# Pin Alice's initial state so arms are compared under "identical
# initial settings" (Sec 4.3).
need_states = {
"Alice": init_need_state_from_profile(
random.Random(seed), baseline_current=6.0
)
}
pre_state = {
"category_means": need_states["Alice"].category_means(),
"needs_current": dict(need_states["Alice"].current),
}
pre = survey_rses(surveyor, pre_state, "Alice, a 14-year-old student")
log(f"claim3: arm={arm} seed={seed} ...")
try:
ep = run_episode(
scenario, "EduMirror", agent_llm, seed=seed,
need_states=need_states, concurrency=args.concurrency,
)
except Exception as exc: # noqa: BLE001
log(f" EPISODE FAILED: {exc}")
continue
alice = ep.internal_states.get("Alice", {})
post = survey_rses(surveyor, alice, "Alice, a 14-year-old student")
# Internal metric: mean of the two self-esteem sub-dimensions
# (Appendix F.5's delta-Value definition).
esteem_dims = ("self worth", "sense of respect")
pre_val = statistics.mean(pre_state["needs_current"][d] for d in esteem_dims)
post_val = statistics.mean(
alice.get("needs_current", pre_state["needs_current"])[d] for d in esteem_dims
)
records.append({
"arm": arm,
"seed": seed,
"rses_pre": pre["total"],
"rses_post": post["total"],
"rses_valid": pre["valid"] and post["valid"],
"delta_rses": (post["total"] - pre["total"])
if (pre["valid"] and post["valid"]) else None,
"value_pre": round(pre_val, 3),
"value_post": round(post_val, 3),
"delta_value": round(post_val - pre_val, 3),
**{f"cat_{k}": round(v, 3)
for k, v in alice.get("category_means", {}).items()},
})
ep.save(out / "episodes" / f"bullying_{arm}_{seed}.json")
# Construct validity: does the external instrument track the internal state?
paired = [
(r["delta_value"], r["delta_rses"])
for r in records
if r["delta_rses"] is not None
]
correlation = None
if len(paired) >= 3:
xs, ys = zip(*paired)
# Guard: correlation is undefined if either series is constant, which
# happens when a small mock/smoke run produces no variation.
if len(set(xs)) > 1 and len(set(ys)) > 1:
correlation = statistics.correlation(xs, ys)
results = {
"records": records,
"delta_value_vs_delta_rses_correlation": correlation,
"n_paired": len(paired),
}
write_json(out / "claim3.json", results)
write_csv(out / "claim3_records.csv", records)
log(f"claim3: correlation(delta_value, delta_RSES) = {correlation} over n={len(paired)}")
return results
# -----------------------------------------------------------------------------
# Claim 4: pairwise win-rate heatmap (Figure 4).
# -----------------------------------------------------------------------------
def stage_claim4(out: Path, args) -> dict:
"""
Run pairwise comparisons among all methods across the scenario suite.
Args:
out: Output directory.
args: Parsed CLI args.
Returns:
Results dict with the win-rate matrix and every individual verdict.
Why we generate once and compare many times:
Each method produces one transcript per (scenario, seed); all pairwise
comparisons then reuse those transcripts. Regenerating per comparison
would cost O(pairs) episodes instead of O(methods) and would also mean
A-vs-B and A-vs-C judged *different* A transcripts, adding variance that
has nothing to do with the methods.
"""
agent_llm = llm_from_env("agent")
judge = llm_from_env("judge")
rng = random.Random(1234)
scenarios = representative_scenarios()
scenarios += [bullying_scenario("neglectful", n_steps=args.n_steps)]
scenarios += [study_group_scenario(), class_task_scenario(),
election_scenario("neglectful")]
total_available = len(scenarios)
if args.max_scenarios:
scenarios = scenarios[: args.max_scenarios]
# Claim 4 is O(scenarios x methods x seeds) episodes and is by far the most
# expensive stage, so it gets its own seed count. Log any truncation loudly:
# a silently-capped suite would read as "covered everything" when it did not.
n_seeds = args.n_seeds_claim4 or args.n_seeds
if len(scenarios) < total_available:
log(f"claim4: NOTE capped to {len(scenarios)}/{total_available} scenarios "
f"(paper evaluates 17); seeds={n_seeds}")
log(f"claim4: {len(scenarios)} scenarios x {len(METHODS)} methods x {n_seeds} seeds "
f"= {len(scenarios) * len(METHODS) * n_seeds} episodes")
# Stage 1: generate one transcript per (scenario, method, seed).
transcripts: dict[tuple[str, str, int], str] = {}
for scenario in scenarios:
for method in METHODS:
for seed in range(n_seeds):
log(f"claim4: gen {scenario.key}/{method}/{seed}")
try:
ep = run_episode(scenario, method, agent_llm, seed=seed,
concurrency=args.concurrency)
transcripts[(scenario.key, method, seed)] = ep.behaviour_text()
except Exception as exc: # noqa: BLE001
log(f" FAILED: {exc}")
# Stage 2: pairwise judging over the generated transcripts.
verdicts: list[dict] = []
for scenario in scenarios:
for i, m_a in enumerate(METHODS):
for m_b in METHODS[i + 1 :]:
for seed in range(n_seeds):
ta = transcripts.get((scenario.key, m_a, seed))
tb = transcripts.get((scenario.key, m_b, seed))
if not ta or not tb:
continue
winner = pairwise_compare(judge, ta, tb, scenario.setting, rng)
verdicts.append({
"scenario": scenario.key, "method_a": m_a, "method_b": m_b,
"seed": seed,
"winner": {"A": m_a, "B": m_b}.get(winner),
})
# Build the win-rate matrix: matrix[row][col] = win rate of COLUMN vs ROW,
# matching the paper's Figure 4 convention ("the win rate of the column
# model relative to the row model").
matrix: dict[str, dict[str, float]] = {r: {} for r in METHODS}
for row in METHODS:
for col in METHODS:
if row == col:
matrix[row][col] = float("nan")
continue
wins = sum(
1 for v in verdicts
if {v["method_a"], v["method_b"]} == {row, col} and v["winner"] == col
)
losses = sum(
1 for v in verdicts
if {v["method_a"], v["method_b"]} == {row, col} and v["winner"] == row
)
matrix[row][col] = win_rate(wins, losses)
# Average win rate per method across all opponents (the paper's headline
# "strongest overall performance in terms of average win rates").
avg_win = {}
for m in METHODS:
vals = [matrix[r][m] for r in METHODS if r != m and matrix[r][m] == matrix[r][m]]
avg_win[m] = round(statistics.mean(vals), 3) if vals else None
results = {
"matrix": matrix, "average_win_rate": avg_win, "verdicts": verdicts,
"n_scenarios": len(scenarios),
"n_scenarios_available": total_available,
"n_scenarios_paper": 17,
"n_seeds": n_seeds,
"scenarios": [s.key for s in scenarios],
}
write_json(out / "claim4.json", results)
write_csv(out / "claim4_verdicts.csv", verdicts)
log(f"claim4 average win rates: {json.dumps(avg_win)}")
return results
# -----------------------------------------------------------------------------
# Claim 5: election intervention strategies (Figure 7).
# -----------------------------------------------------------------------------
def stage_claim5(out: Path, args) -> dict:
"""
Compare the three intervention strategies against the neglectful control.
Args:
out: Output directory.
args: Parsed CLI args.
Returns:
Results dict with per-arm malicious-competition counts and dispersion.
Why dispersion, not just the mean:
Claim 5 is specifically that interventions "mitigate extreme competitive
tendencies and foster more balanced cooperation", and the paper's
supporting evidence is about spread: "Their lower variance and narrower
ranges across repeated simulations suggest a genuine balancing effect
rather than random fluctuation", with the control showing "the widest
fluctuation". So the testable quantity is the VARIANCE/range of malicious
competition per arm, not only its mean. We record both.
"""
agent_llm = llm_from_env("agent")
judge = llm_from_env("judge")
records: list[dict] = []
for arm in ELECTION_INTERVENTIONS:
scenario = election_scenario(arm, n_agents=args.election_agents,
n_steps=args.n_steps)
for seed in range(args.n_seeds_claim5):
log(f"claim5: arm={arm} seed={seed}")
try:
ep = run_episode(scenario, "EduMirror", agent_llm, seed=seed,
concurrency=args.concurrency)
except Exception as exc: # noqa: BLE001
log(f" FAILED: {exc}")
continue
coded = rate_competition(judge, ep.behaviour_text(), scenario.setting)
# Also validate the Social Value System: does a Surveyor-measured
# SVO angle recover each agent's internal target? (Figure 10.)
svo_rows = []
for persona in scenario.personas:
st = ep.internal_states.get(persona.name, {})
measured = survey_svo(
judge, f"{persona.name}: {persona.description} {persona.goal}",
st.get("svo_target"),
)
svo_rows.append({
"agent": persona.name,
"target": st.get("svo_target"),
"internal_angle": st.get("svo_mean_angle_deg"),
"measured_angle": measured["angle"],
"valid": measured["valid"],
})
records.append({
"arm": arm, "seed": seed,
"cooperative": coded["cooperative"],
"competitive": coded["competitive"],
"malicious_competition": coded["malicious_competition"],
"valid": coded["valid"],
"svo": svo_rows,
})
ep.save(out / "episodes" / f"election_{arm}_{seed}.json")
summary: dict[str, dict] = {}
for arm in ELECTION_INTERVENTIONS:
vals = [r["malicious_competition"] for r in records
if r["arm"] == arm and r["valid"]]
coop = [r["cooperative"] for r in records if r["arm"] == arm and r["valid"]]
if vals:
summary[arm] = {
"n": len(vals),
"malicious_mean": round(statistics.mean(vals), 3),
"malicious_stdev": round(statistics.stdev(vals), 3) if len(vals) > 1 else 0.0,
"malicious_min": min(vals),
"malicious_max": max(vals),
"malicious_range": max(vals) - min(vals),
"cooperative_mean": round(statistics.mean(coop), 3) if coop else None,
}
flat = [{k: v for k, v in r.items() if k != "svo"} for r in records]
results = {"records": records, "summary": summary}
write_json(out / "claim5.json", results)
write_csv(out / "claim5_records.csv", flat)
log(f"claim5 summary: {json.dumps(summary)}")
return results
# -----------------------------------------------------------------------------
# Smoke.
# -----------------------------------------------------------------------------
def stage_smoke(out: Path, args) -> dict:
"""
Tiny end-to-end run over every method and every measurement path.
Args:
out: Output directory.
args: Parsed CLI args.
Returns:
A dict of per-method smoke results.
Why:
Exercises the exact code path the GPU job will take -- every
architecture, the GM loop, the Rater, and the Surveyor -- so plumbing
bugs surface locally in seconds instead of 40 minutes into a paid job.
"""
agent_llm = llm_from_env("agent")
judge = llm_from_env("judge")
scenario = kindergarten_scenario(n_agents=3, n_steps=2)
results = {}
for method in METHODS:
ep = run_episode(scenario, method, agent_llm, seed=0, concurrency=args.concurrency)
rating = rate_behaviour(judge, ep.behaviour_text(), scenario.setting)
results[method] = {
"steps": len(ep.transcript),
"scores": rating.scores,
"average": rating.average(list(RATING_METRICS)),
"usage": ep.usage,
}
log(f"smoke {method}: avg={rating.average(list(RATING_METRICS))}")
write_json(out / "smoke.json", results)
return results
def stage_judgecheck(out: Path, args) -> dict:
"""
Test whether the LLM judge can discriminate quality at all, before trusting it.
Args:
out: Output directory.
args: Parsed CLI args.
Returns:
{"absolute": {...}, "pairwise": {...}} probe results.
Why this runs FIRST:
Our initial GPU run scored every episode exactly 4.0 across all methods
and seeds -- a broken instrument, not a tie. Reporting that as "the
methods are equivalent" would be reporting instrument failure as a
finding. This stage generates one real transcript, corrupts it in ways we
KNOW make it worse (shuffled order, robotic actions), and checks the
judge notices. If it does not, every judged claim downstream is
uninterpretable and the logbook must say so rather than publish numbers.
"""
judge = llm_from_env("judge")
rng = random.Random(7)
scenario = kindergarten_scenario(n_agents=5, n_steps=args.n_steps)
if args.reference_episode:
# JUDGE-ONLY MODE. The probe needs one reference transcript, and it does
# not matter who generated it -- the corruptions are applied to whatever
# it is, and every judge is compared against the SAME text. Reusing an
# archived episode therefore costs zero agent calls, which is what makes
# probing an expensive frontier judge cost cents rather than dollars.
# It also removes a confound: every judge now grades byte-identical text.
ep_data = json.loads(Path(args.reference_episode).read_text())
chunks = []
for entry in ep_data["transcript"]:
chunks.append(f"--- Step {entry['step']} ({entry['location']}) ---")
chunks.append(entry["narration"])
for name, action in entry["actions"].items():
chunks.append(f"{name}: {action}")
transcript = "\n".join(chunks)
log(f"judgecheck: reusing archived reference transcript "
f"({args.reference_episode}, {len(transcript)} chars, "
f"{len(ep_data['transcript'])} steps) -- ZERO agent calls")
else:
agent_llm = llm_from_env("agent")
log("judgecheck: generating one reference transcript (EduMirror) ...")
ep = run_episode(scenario, "EduMirror", agent_llm, seed=0,
concurrency=args.concurrency)
transcript = ep.behaviour_text()
log("judgecheck: probing ABSOLUTE rater (real vs corrupted) ...")
absolute = probe_absolute(judge, transcript, scenario.setting, rng)
log(f" ABSOLUTE verdict={absolute['verdict']} real_avg={absolute['real']['average']} "
f"margins={absolute['margins']}")
log("judgecheck: probing PAIRWISE judge (real vs corrupted) ...")
pairwise = probe_pairwise(judge, transcript, scenario.setting, rng,
n_trials=args.judge_trials)
log(f" PAIRWISE verdict={pairwise['verdict']} "
f"{ {k: v for k, v in pairwise.items() if k in CORRUPTION_KEYS} }")
results = {"absolute": absolute, "pairwise": pairwise,
"reference_transcript_chars": len(transcript),
"judge_usage": judge.usage.as_dict()}
write_json(out / "judgecheck.json", results)
log(f"JUDGECHECK VERDICT: absolute={absolute['verdict']} pairwise={pairwise['verdict']}")
# An UNREADABLE verdict is OUR bug, not a finding about the model. Say so
# loudly and show the evidence, so nobody reads it as "the judge is blind".
for track, res in (("absolute", absolute), ("pairwise", pairwise)):
if res["verdict"] == "UNREADABLE":
log(f" !! {track}: output was UNPARSEABLE -- this is a HARNESS problem, "
f"NOT evidence the judge cannot discriminate.")
for s in res.get("unreadable_samples", [])[:1]:
log(f" raw sample: {s[:400]!r}")
u = judge.usage.as_dict()
if u.get("truncated"):
log(f" !! {u['truncated']}/{u['calls']} judge responses hit max_tokens "
f"(finish_reason=length) -- raise EDUMIRROR_JUDGE_MAX_TOKENS.")
return results
STAGES = {
"smoke": stage_smoke,
"judgecheck": stage_judgecheck,
"claim2": stage_claim2,
"claim3": stage_claim3,
"claim4": stage_claim4,
"claim5": stage_claim5,
}
def main() -> None:
"""Parse args and run the requested stage(s)."""
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--stage", default="smoke",
choices=list(STAGES) + ["all"], help="which experiment to run")
p.add_argument("--judge-trials", type=int, default=6,
help="pairwise trials per corruption in the judgecheck stage")
p.add_argument("--reference-episode", type=str, default="",
help="path to an archived episode JSON to use as the probe's "
"reference transcript. Enables JUDGE-ONLY mode: no agent "
"calls at all, so probing a paid frontier judge costs "
"cents. Also removes a confound -- every judge then "
"grades byte-identical text.")
p.add_argument("--out", type=Path, default=Path("outputs"))
p.add_argument("--group-sizes", type=int, nargs="+", default=[5, 15, 30],
help="kindergarten group sizes (paper: 5 15 30)")
p.add_argument("--n-steps", type=int, default=8)
p.add_argument("--n-seeds", type=int, default=3,
help="episodes per cell; higher = less noise, more cost")
p.add_argument("--n-seeds-claim5", type=int, default=8,
help="repeats per intervention arm; Claim 5 is about VARIANCE, "
"so it needs more repeats than the mean-based claims")
p.add_argument("--n-seeds-claim4", type=int, default=0,
help="seeds for the pairwise heatmap (0 = use --n-seeds). "
"Claim 4 is the most expensive stage (scenarios x methods "
"x seeds episodes), so it gets its own knob")
p.add_argument("--election-agents", type=int, default=5)
p.add_argument("--max-scenarios", type=int, default=0,
help="cap scenarios in claim4 (0 = all)")
p.add_argument("--concurrency", type=int, default=16)
args = p.parse_args()
out = args.out
out.mkdir(parents=True, exist_ok=True)
stages = ["judgecheck", "claim2", "claim3", "claim4", "claim5"] if args.stage == "all" else [args.stage]
manifest = {"stages": stages, "args": vars(args), "started": time.time()}
t0 = time.time()
for stage in stages:
log(f"=== STAGE {stage} ===")
STAGES[stage](out, args)
manifest["elapsed_s"] = round(time.time() - t0, 1)
write_json(out / "manifest.json", manifest)
log(f"DONE in {manifest['elapsed_s']}s -> {out}")
if __name__ == "__main__":
main()