"""Score results/*.jsonl against gold labels. Writes scores.json and numbers.tex; prints a summary. Primary outcome: invented deadlines on the 60 items with no firm deadline. Hypotheses, stated before any Gemma run (not formally pre-registered): H1 the guarded prompt invents fewer deadlines than the plain prompt (thinking off, the pipeline's setting) H2 thinking on invents fewer deadlines than thinking off (plain prompt) Both are tested per model with an exact McNemar test on the same 60 items. """ import collections, glob, json, math, re ZONES = { "america/los_angeles": ["pt", "pst", "pdt", "pacific", "us/pacific", "america/los_angeles"], "america/new_york": ["et", "est", "edt", "eastern", "us/eastern", "america/new_york"], "europe/berlin": ["cet", "cest", "europe/berlin", "europe/paris", "europe/amsterdam", "europe/brussels", "europe/madrid", "europe/rome"], "etc/gmt+12": ["aoe", "anywhere on earth", "etc/gmt+12", "utc-12", "utc-12:00", "gmt-12"], "asia/singapore": ["sgt", "asia/singapore"], "utc": ["utc", "etc/utc", "gmt", "etc/gmt", "z", "zulu"], } ALIAS = {a: canon for canon, names in ZONES.items() for a in names} METRICS = ["parsed", "fabricated", "missed", "date_correct", "date_wrong", "time_correct", "tz_correct", "tz_correct_aoe", "tz_correct_named", "invented_time", "added_tz", "added_tz_not_recording", "alarm_correct", "alarm_wrong", "alarm_set_due", "alarm_set_not_due"] # the 13 phrasings of the three no-deadline kinds (make_items.py), found by a substring unique to each PHRASINGS = { "PlaceholderCalendar": "just a placeholder", "PlaceholderTbd": "placeholder, to be confirmed", "PlaceholderGuess": "as a guess", "PlaceholderFlyer": "old flyer", "CondCard": "card arrives", "CondRolling": "rolling admissions", "CondLawyer": "approval notice", "CondInterview": "scheduled the interview", "NoneSomePoint": "at some point", "NoneMom": "call my mom", "NoneEventually": "eventually, whenever", "NoneMaybe": "not urgent", "NoneRunning": "start running", } KINDS = {"voice_memo": "Voice", "wearable": "Wearable", "email": "Email"} def phrasing(text): hits = [k for k, s in PHRASINGS.items() if s in text] return hits[0] if len(hits) == 1 else None def zone(z): return ALIAS.get(str(z).strip().lower(), str(z).strip().lower()) if z else None def wilson(k, n, z=1.96): if n == 0: return [None, None] p, d = k / n, 1 + z * z / n c, h = p + z * z / (2 * n), z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) return [(c - h) / d, (c + h) / d] def mcnemar_exact(b, c): """Two-sided exact binomial test on the discordant pairs.""" n = b + c if n == 0: return 1.0 tail = sum(math.comb(n, i) for i in range(0, min(b, c) + 1)) / 2 ** n return min(1.0, 2 * tail) def judge(r): g, p = r["gold"], r["pred"] or {} pred_has = bool(p.get("has_deadline")) and bool(p.get("deadline_date")) alarm = bool(p.get("should_set_alarm")) out = {"parsed": r["pred"] is not None, "alarm_correct": alarm == g["should_set_alarm"], "alarm_wrong": alarm != g["should_set_alarm"]} out["alarm_set_due" if g["should_set_alarm"] else "alarm_set_not_due"] = alarm if g["has_deadline"]: out["missed"] = not pred_has out["date_correct"] = pred_has and str(p.get("deadline_date")) == g["deadline_date"] out["date_wrong"] = not out["date_correct"] if g["deadline_time"]: out["time_correct"] = str(p.get("deadline_time") or "")[:5] == g["deadline_time"] out["tz_correct"] = zone(p.get("timezone")) == zone(g["timezone"]) # AoE (Anywhere on Earth, UTC-12) is the last zone on Earth, so any other zone moves the deadline earlier out["tz_correct_aoe" if zone(g["timezone"]) == "etc/gmt+12" else "tz_correct_named"] = out["tz_correct"] else: # a clock time that was never said is an invention; a timezone is usually the recording's own zone, # a default rather than an invention, so it is counted separately out["invented_time"] = bool(p.get("deadline_time")) out["added_tz"] = bool(p.get("timezone")) # every recording time is stamped Pacific; a zone other than that is not a default out["added_tz_not_recording"] = bool(p.get("timezone")) and zone(p.get("timezone")) != "america/los_angeles" else: out["fabricated"] = pred_has return out def rate(rs, key): xs = [r["judge"][key] for r in rs if key in r["judge"]] k, n = sum(xs), len(xs) return {"k": k, "n": n, "rate": k / n if n else None, "ci95": wilson(k, n)} def paired(by, a, b, key): """Items where condition a and b disagree on `key`: b_ = a yes & b no, c_ = a no & b yes.""" A = {r["id"]: r["judge"][key] for r in by.get(a, []) if key in r["judge"]} B = {r["id"]: r["judge"][key] for r in by.get(b, []) if key in r["judge"]} ids = sorted(set(A) & set(B)) b_ = sum(A[i] and not B[i] for i in ids) c_ = sum(B[i] and not A[i] for i in ids) return {"a": a, "b": b, "metric": key, "n": len(ids), "a_only": b_, "b_only": c_, "rate_a": sum(A[i] for i in ids) / len(ids) if ids else None, "rate_b": sum(B[i] for i in ids) / len(ids) if ids else None, "p_exact": mcnemar_exact(b_, c_)} ITEMS = {json.loads(l)["id"]: json.loads(l) for l in open("items.jsonl")} unmatched = [i for i, it in ITEMS.items() if not it["gold"]["has_deadline"] and phrasing(it["text"]) is None] if unmatched: raise SystemExit(f"phrasing table does not cover {unmatched}") scores = {} for path in sorted(glob.glob("results/*.jsonl")): rows = [json.loads(l) for l in open(path)] model = rows[0]["model"] by = collections.defaultdict(list) for r in rows: r["judge"] = judge(r) r["phrasing"] = phrasing(r.get("text") or ITEMS[r["id"]]["text"]) if not r["gold"]["has_deadline"] else None by[r["condition"]].append(r) M = {"file": path, "conditions": {}} for cond, rs in sorted(by.items()): s = {m: rate(rs, m) for m in METRICS} s["by_family"] = {} for fam in sorted({r["family"] for r in rs}): fr = [r for r in rs if r["family"] == fam] key = "fabricated" if not fr[0]["gold"]["has_deadline"] else "date_correct" s["by_family"][fam] = {"metric": key, **rate(fr, key), "alarm_correct": rate(fr, "alarm_correct")["rate"]} s["by_phrasing"] = {} for ph in PHRASINGS: pr = [r for r in rs if r["phrasing"] == ph] s["by_phrasing"][ph] = {"all": rate(pr, "fabricated"), **{kk: rate([r for r in pr if r["capture_kind"] == kind], "fabricated") for kind, kk in KINDS.items()}} toks = [((r.get("usage") or {}).get("completion_tokens") or 0) for r in rs] s["mean_completion_tokens"] = sum(toks) / len(toks) s["mean_latency_s"] = sum(r["latency_s"] for r in rs) / len(rs) s["n_answers"] = len(rs) M["conditions"][cond] = s if "plain_nothink" in by and "plain_nothink_rep" in by: a = {r["id"]: r["pred"] or {} for r in by["plain_nothink"]} b = {r["id"]: r["pred"] or {} for r in by["plain_nothink_rep"]} same = [(a[i].get("has_deadline"), a[i].get("deadline_date")) == (b[i].get("has_deadline"), b[i].get("deadline_date")) for i in a if i in b] M["noise_floor"] = {"identical_answer_rate": sum(same) / len(same), "n": len(same), "fabricated_rep": paired(by, "plain_nothink", "plain_nothink_rep", "fabricated")} M["tests"] = { "H1_guarded_vs_plain_fabricated": paired(by, "plain_nothink", "guarded_nothink", "fabricated"), "H2_think_vs_nothink_fabricated": paired(by, "plain_nothink", "plain_think", "fabricated"), "guarded_think_vs_guarded_nothink_fabricated": paired(by, "guarded_nothink", "guarded_think", "fabricated"), "guarded_vs_plain_date_correct": paired(by, "plain_nothink", "guarded_nothink", "date_correct"), "think_vs_nothink_date_correct": paired(by, "plain_nothink", "plain_think", "date_correct"), } scores[model] = M json.dump(scores, open("scores.json", "w"), indent=1) # numbers.tex: every number the paper quotes, written by this script, never typed by hand def macro(name): return re.sub(r"[^A-Za-z]", "", name.title()) def model_key(model): return macro(model.replace("gemma4:", "gemma").replace("31b", "ThirtyOne").replace("12b", "Twelve")) # design counts, computed from items.jsonl rather than typed lines = [f"\\newcommand{{\\Phrase{ph}N}}{{{sum(phrasing(it['text']) == ph for it in ITEMS.values())}}}" for ph in PHRASINGS] lines.append(f"\\newcommand{{\\AoeN}}{{{sum(zone(it['gold']['timezone']) == 'etc/gmt+12' for it in ITEMS.values())}}}") for ph in PHRASINGS: for kind, kk in KINDS.items(): n = sum(phrasing(it["text"]) == ph and it["capture_kind"] == kind for it in ITEMS.values()) lines.append(f"\\newcommand{{\\Phrase{ph}{kk}N}}{{{n}}}") for model, M in scores.items(): mk = model_key(model) for cond, s in M["conditions"].items(): ck = macro(cond) for m in METRICS: v = s[m] if v["n"]: lines.append(f"\\newcommand{{\\{mk}{ck}{macro(m)}}}{{{100 * v['rate']:.0f}\\%}}") lines.append(f"\\newcommand{{\\{mk}{ck}{macro(m)}K}}{{{v['k']}/{v['n']}}}") lines.append(f"\\newcommand{{\\{mk}{ck}{macro(m)}CI}}{{[{100 * v['ci95'][0]:.0f}, {100 * v['ci95'][1]:.0f}]}}") lines.append(f"\\newcommand{{\\{mk}{ck}{macro(m)}CIHi}}{{{100 * v['ci95'][1]:.0f}\\%}}") for ph, v in s["by_phrasing"].items(): for part, pv in v.items(): if pv["n"]: suffix = "" if part == "all" else part lines.append(f"\\newcommand{{\\{mk}{ck}Fab{ph}{suffix}K}}{{{pv['k']}/{pv['n']}}}") lines.append(f"\\newcommand{{\\{mk}{ck}Tokens}}{{{s['mean_completion_tokens']:.0f}}}") lines.append(f"\\newcommand{{\\{mk}{ck}Latency}}{{{s['mean_latency_s']:.0f}}}") C = M["conditions"] if "plain_think" in C and "plain_nothink" in C: lines.append(f"\\newcommand{{\\{mk}ThinkSlowdown}}{{{C['plain_think']['mean_latency_s'] / C['plain_nothink']['mean_latency_s']:.0f}}}") lines.append(f"\\newcommand{{\\{mk}ThinkTokenRatio}}{{{C['plain_think']['mean_completion_tokens'] / C['plain_nothink']['mean_completion_tokens']:.0f}}}") for t, v in M["tests"].items(): tk = macro(t) lines.append(f"\\newcommand{{\\{mk}{tk}P}}{{{v['p_exact']:.3g}}}") lines.append(f"\\newcommand{{\\{mk}{tk}Disc}}{{{v['a_only']} vs {v['b_only']}}}") # the smallest p this many disagreements could give, had they all gone one way lines.append(f"\\newcommand{{\\{mk}{tk}PMin}}{{{mcnemar_exact(v['a_only'] + v['b_only'], 0):.3g}}}") if "noise_floor" in M: nf = M["noise_floor"] lines.append(f"\\newcommand{{\\{mk}NoiseSame}}{{{100 * nf['identical_answer_rate']:.0f}\\%}}") lines.append(f"\\newcommand{{\\{mk}NoiseDiffer}}{{{round((1 - nf['identical_answer_rate']) * nf['n'])}}}") allrows = [(m, c, s) for m, M in scores.items() for c, s in M["conditions"].items()] lines.append(f"\\newcommand{{\\PhrasingsN}}{{{len(PHRASINGS)}}}") lines.append(f"\\newcommand{{\\TotalAnswers}}{{{sum(s['n_answers'] for _, _, s in allrows):,}}}") lines.append(f"\\newcommand{{\\TotalParsed}}{{{sum(s['parsed']['k'] for _, _, s in allrows):,}}}") lines.append(f"\\newcommand{{\\MissedAll}}{{{sum(s['missed']['k'] for _, _, s in allrows)}}}") lines.append(f"\\newcommand{{\\FabricatedAll}}{{{sum(s['fabricated']['k'] for _, _, s in allrows)}}}") open("numbers.tex", "w").write("\n".join(lines) + "\n") # appendix tables: every outcome, every setup, one table per model, counts written by this script ROWS = [("Invented a deadline", "fabricated", [("placeholder_date", "date marked placeholder"), ("conditional_undated", "depends on an event"), ("no_deadline", "no deadline at all")]), ("Correct date", "date_correct", [("explicit_date", "date stated outright"), ("relative_date", "relative date"), ("event_vs_deadline", "event date next to deadline"), ("clock_and_timezone", "clock time and timezone")])] EXTRA = [("Correct clock time, when one is stated", "time_correct"), ("Correct timezone, when one is stated", "tz_correct"), ("\\quad of which AoE (Anywhere on Earth)", "tz_correct_aoe"), ("Clock time given though none was said", "invented_time"), ("Timezone given though none was said", "added_tz"), ("Alarm set, firm deadline", "alarm_set_due"), ("Alarm set, no firm deadline", "alarm_set_not_due"), ("Alarm decision correct", "alarm_correct"), ("Mean output tokens", "tokens")] ORDER = ["plain_nothink", "plain_nothink_rep", "plain_think", "guarded_nothink", "guarded_think"] HEAD = ["Plain, off", "Plain, off (repeat)", "Plain, on", "Guarded, off", "Guarded, on"] for model, M in scores.items(): conds = [c for c in ORDER if c in M["conditions"]] C = M["conditions"] t = ["\\begin{tabular}{@{}l" + "r" * len(conds) + "@{}}", "\\toprule", "& " + " & ".join(HEAD[ORDER.index(c)] for c in conds) + " \\\\", "\\midrule"] for title, key, fams in ROWS: t.append(f"\\multicolumn{{{len(conds) + 1}}}{{@{{}}l}}{{\\emph{{{title} (of 20 each)}}}} \\\\") for fam, label in fams: t.append(f"\\quad {label} & " + " & ".join(str(C[c]["by_family"][fam]["k"]) if fam in C[c]["by_family"] else "" for c in conds) + " \\\\") t.append("\\midrule") for label, key in EXTRA: cells = [f"{C[c]['mean_completion_tokens']:.0f}" if key == "tokens" else (str(C[c][key]["k"]) if C[c][key]["n"] else "") for c in conds] n = "" if key == "tokens" else f" (of {C[ORDER[0]][key]['n']})" t.append(f"{label}{n} & " + " & ".join(cells) + " \\\\") t += ["\\bottomrule", "\\end{tabular}"] open(f"paper/table_{model_key(model)}.tex", "w").write("\n".join(t) + "\n") for model, M in scores.items(): print(f"\n######## {model}") for cond, s in M["conditions"].items(): f = lambda m: f"{s[m]['k']}/{s[m]['n']} ({s[m]['rate']:.0%})" if s[m]["n"] else "-" print(f"== {cond:18s} n={s['n_answers']} parsed {f('parsed')} tokens {s['mean_completion_tokens']:.0f} {s['mean_latency_s']:.1f}s") print(f" invented {f('fabricated')} missed {f('missed')} date {f('date_correct')} time {f('time_correct')} tz {f('tz_correct')} invented time {f('invented_time')} added tz {f('added_tz')} alarm {f('alarm_correct')}") print(" " + " ".join(f"{fam[:12]}={v['k']}/{v['n']}" for fam, v in s["by_family"].items())) if "noise_floor" in M: print(f"noise floor: identical {M['noise_floor']['identical_answer_rate']:.0%} of {M['noise_floor']['n']}") for t, v in M["tests"].items(): print(f"test {t}: {v['rate_a']:.0%} -> {v['rate_b']:.0%} discordant {v['a_only']} vs {v['b_only']} p={v['p_exact']:.3g}" if v["n"] else f"test {t}: no data")