code-switch-mtp / scripts /phase2b_aggregate.py
Anupam-Rawat-IITB's picture
Add code, result files and documentation
3bbd5dd verified
Raw History Blame Contribute Delete
4.58 kB
"""Aggregate Phase 2b per-cell outputs into results/phase2b_blockers.csv.
Blocker A's four cells are measured over one shared sentence subset, so the
cross-cell contrasts here are paired differences rather than differences of
independent means. The two contrasts that matter:
model effect = (sarvam - llama) computed within each script, twice
script effect = (devanagari - romanized) computed within each model, twice
A model effect that holds its sign and magnitude across both scripts points
at model identity as the driver of the Phase 2 L1 anomaly; one that flips or
vanishes when the script changes points at a genuine script/fertility
interaction.
"""
import argparse
import csv
import json
import logging
from pathlib import Path
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger("phase2b_agg")
import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from src.measure.uncertainty import mean_estimate, paired_difference
A_CELLS = ("sarvam_dev", "sarvam_rom", "llama_dev", "llama_rom")
A_METRICS = ("fertility", "d_indep_k2", "d_indep_k3")
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--in-dir", required=True)
p.add_argument("--out", default="results/phase2b_blockers.csv")
p.add_argument("--resamples", type=int, default=2000)
return p.parse_args()
def rows_for_blocker_a(in_dir: Path, resamples: int) -> list:
cells = {}
for cell in A_CELLS:
path = in_dir / f"a_{cell}.json"
if not path.exists():
logger.warning("missing %s, skipping cell %s", path, cell)
continue
cells[cell] = json.loads(path.read_text())
rows = []
for cell, data in cells.items():
for metric in A_METRICS:
est = mean_estimate(data[metric], resamples=resamples)
rows.append((cell, metric, est.mean, est.n))
rows.append((cell, f"{metric}_stderr", est.stderr, est.n))
rows.append((cell, f"{metric}_ci_low", est.ci_low, est.n))
rows.append((cell, f"{metric}_ci_high", est.ci_high, est.n))
contrasts = [
("model_effect_devanagari", "sarvam_dev", "llama_dev"),
("model_effect_romanized", "sarvam_rom", "llama_rom"),
("script_effect_sarvam", "sarvam_dev", "sarvam_rom"),
("script_effect_llama", "llama_dev", "llama_rom"),
]
for name, a, b in contrasts:
if a not in cells or b not in cells:
continue
for metric in A_METRICS:
est = paired_difference(cells[a][metric], cells[b][metric], resamples=resamples)
rows.append((name, f"{metric}_paired_diff", est.mean, est.n))
rows.append((name, f"{metric}_paired_diff_stderr", est.stderr, est.n))
rows.append((name, f"{metric}_paired_diff_ci_low", est.ci_low, est.n))
rows.append((name, f"{metric}_paired_diff_ci_high", est.ci_high, est.n))
return rows
B_OUTPUTS = (
("b_arch.json", "B_arch"),
("b_trough_L5.json", "B_trough_L5"),
("b_trough_L1.json", "B_trough_L1"),
("b_trough_L4.json", "B_trough_L4"),
)
def rows_for_blocker_b(in_dir: Path) -> list:
rows = []
for name, label in B_OUTPUTS:
path = in_dir / name
if not path.exists():
logger.warning("missing %s", path)
continue
data = json.loads(path.read_text())
for key, entry in data.items():
cond = f"{label}__{key}"
rows.append((cond, "entropy_trough_depth", entry["entropy_trough_depth"], entry["n_points"]))
rows.append((cond, "n_h1_intraword", len(entry["h1_intraword_values"]), entry["n_points"]))
rows.append((cond, "n_h1_boundary", len(entry["h1_boundary_values"]), entry["n_points"]))
for metric, value in entry.get("by_horizon", {}).items():
rows.append((cond, metric, value, entry["n_points"]))
return rows
def main() -> None:
args = parse_args()
in_dir = Path(args.in_dir)
rows = rows_for_blocker_a(in_dir, args.resamples) + rows_for_blocker_b(in_dir)
Path(args.out).parent.mkdir(parents=True, exist_ok=True)
with open(args.out, "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["condition", "metric", "value", "n"])
for cond, metric, value, n in rows:
writer.writerow([cond, metric, value, n])
logger.info("wrote %s (%d rows)", args.out, len(rows))
if __name__ == "__main__":
main()