carlostoxtli's picture
Upload MAUI-Bench v1.0.0
7c188b6 verified
Raw History Blame Contribute Delete
9.65 kB
"""Trace annotation for the MAUX coverage study (Section 6.5 of the paper).
Two stages:
1. Sample: stratified sample of traces (balanced over topology, family, and
regret quartile), exported to results/<run_id>/annotation/sample.jsonl and
an editable CSV for the two human author annotators.
python src/analysis/annotate.py sample --run-id RUN --n 600
2. Judge: LLM-judge pass with a locked rubric prompt against the configured
judge model (annotation.judge_model in config/experiment.yaml), writing one
MAUX + MAST label set per trace. Agreement (Cohen's kappa) between judge
and each human, and between humans on the dual-annotated subset, is
computed by the report subcommand.
python src/analysis/annotate.py judge --run-id RUN
python src/analysis/annotate.py report --run-id RUN
"""
from __future__ import annotations
import argparse
import csv
import json
import os
import sys
import numpy as np
import pandas as pd
import yaml
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from client import LLMClient # noqa: E402
MAUX_CODES = ["F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "NONE"]
MAST_CODES = ["SPEC", "MISALIGN", "VERIFY", "NONE"]
RUBRIC = """You are annotating an execution trace of a multi-agent LLM pipeline
serving as the intelligence layer of a user interface. Assign zero or more MAUX
failure codes and zero or more MAST categories.
MAUX codes:
F1 adaptation suboptimality: final answer is far from the declared optimum.
F2 referential inconsistency: output would differ under a paraphrase of the
same request (evident from unstable reasoning tied to surface wording).
F3 temporal inconsistency: reasoning is seed-dependent or arbitrary between
equally described options.
F4 deliberative opacity: committee members disagreed and the disagreement was
dropped or silently averaged rather than resolved or surfaced.
F5 intervention miscalibration: policy over/under-intervenes relative to the
declared cost matrix.
F6 latency unpredictability: a role produced extreme response time relative to
the others (visible in per-call latency fields).
F7 non-graceful degradation: a role failure, empty message, corrupted handoff,
or schema failure propagated into a worse final answer.
F8 resource inefficiency: many tokens spent without improving the answer over
the first proposal.
NONE no MAUX failure.
MAST categories (task-completion failures):
SPEC specification or system design failure; MISALIGN inter-agent
misalignment; VERIFY task verification failure; NONE.
Respond with ONLY JSON: {"maux": [codes], "mast": [codes],
"witness": "one sentence citing the decisive evidence in the trace"}."""
def load_run(results_dir: str, run_id: str):
run_dir = os.path.join(results_dir, run_id)
recs = []
seen = set()
with open(os.path.join(run_dir, "records.jsonl")) as f:
for line in f:
try:
r = json.loads(line)
if r.get("key") != "ERR" and r["key"] not in seen:
seen.add(r["key"])
recs.append(r)
except Exception:
pass
return run_dir, pd.DataFrame(recs)
def cmd_sample(args) -> None:
run_dir, df = load_run(args.results_dir, args.run_id)
adir = os.path.join(run_dir, "annotation")
os.makedirs(adir, exist_ok=True)
df["quartile"] = pd.qcut(df["normalized_regret"].rank(method="first"), 4,
labels=False)
strata = df.groupby(["topology", "family", "quartile"])
per = max(1, args.n // max(len(strata), 1))
rng = np.random.default_rng(7)
keys = []
for _, g in strata:
take = min(per, len(g))
keys += list(g.sample(take, random_state=int(rng.integers(1e9)))["key"])
keys = keys[: args.n]
with open(os.path.join(adir, "sample.jsonl"), "w") as f:
for k in keys:
f.write(json.dumps({"key": k}) + "\n")
# human annotation sheets (dual subset first)
dual = keys[: args.dual]
for annotator in ("A", "B"):
with open(os.path.join(adir, f"human_{annotator}.csv"), "w",
newline="") as f:
w = csv.writer(f)
w.writerow(["key", "maux_codes", "mast_codes", "notes"])
rows = dual if annotator == "B" else keys
for k in rows:
w.writerow([k, "", "", ""])
print(f"[info] sampled {len(keys)} traces ({len(dual)} dual) into {adir}")
def cmd_judge(args) -> None:
with open(args.config) as f:
cfg = yaml.safe_load(f)
judge_model = cfg["annotation"].get("judge_model")
if not judge_model:
print("[error] set annotation.judge_model in config/experiment.yaml")
return
client = LLMClient(base_url=cfg["server"]["base_url"],
api_key=cfg["server"]["api_key"],
timeout_s=cfg["server"]["timeout_s"])
run_dir, _ = load_run(args.results_dir, args.run_id)
adir = os.path.join(run_dir, "annotation")
out_path = os.path.join(adir, "judge.jsonl")
done = set()
if os.path.exists(out_path):
with open(out_path) as f:
done = {json.loads(l)["key"] for l in f if l.strip()}
with open(os.path.join(adir, "sample.jsonl")) as f:
keys = [json.loads(l)["key"] for l in f]
for i, k in enumerate(keys):
if k in done:
continue
tpath = os.path.join(run_dir, "traces", f"{k}.json")
if not os.path.exists(tpath):
continue
with open(tpath) as f:
trace = json.load(f)
# compact the trace for the judge context window
lines = []
for c in trace["calls"]:
lines.append(f"[{c['role']} ok={c['ok']} lat={c['latency_s']:.1f}s "
f"tok={c['completion_tokens']}]\n"
f"{c['completion'][:1500]}")
res = client.chat(judge_model,
[{"role": "system", "content": RUBRIC},
{"role": "user",
"content": "TRACE:\n" + "\n\n".join(lines)[:24000]}],
temperature=0.0, max_tokens=8192)
rec = {"key": k, "ok": res.ok, "raw": res.text, "error": res.error}
with open(out_path, "a") as f:
f.write(json.dumps(rec) + "\n")
if (i + 1) % 25 == 0:
print(f"[judge] {i+1}/{len(keys)}")
print(f"[info] judge annotations at {out_path}")
def _parse_codes(raw: str, valid: list[str], field: str) -> frozenset:
try:
start = raw.find("{")
obj = json.loads(raw[start:raw.rfind("}") + 1])
return frozenset(c for c in obj.get(field, []) if c in valid)
except Exception:
return frozenset()
def cohen_kappa(a: list[frozenset], b: list[frozenset], code: str) -> float:
xa = np.array([code in s for s in a])
xb = np.array([code in s for s in b])
po = float((xa == xb).mean())
pe = float(xa.mean() * xb.mean() + (1 - xa.mean()) * (1 - xb.mean()))
if pe >= 1.0:
return float("nan")
return (po - pe) / (1 - pe)
def cmd_report(args) -> None:
run_dir, _ = load_run(args.results_dir, args.run_id)
adir = os.path.join(run_dir, "annotation")
judge = {}
with open(os.path.join(adir, "judge.jsonl")) as f:
for l in f:
r = json.loads(l)
judge[r["key"]] = (_parse_codes(r.get("raw", ""), MAUX_CODES, "maux"),
_parse_codes(r.get("raw", ""), MAST_CODES, "mast"))
print(f"[info] {len(judge)} judged traces")
counts = {c: sum(1 for m, _ in judge.values() if c in m) for c in MAUX_CODES}
print("MAUX prevalence:", counts)
mast_counts = {c: sum(1 for _, m in judge.values() if c in m)
for c in MAST_CODES}
print("MAST prevalence:", mast_counts)
# disjointness witnesses: MAUX failure with MAST == NONE or empty
witnesses = [k for k, (mx, ms) in judge.items()
if mx and mx != {"NONE"} and (not ms or ms == {"NONE"})]
print(f"MAST-disjoint MAUX failures (witness candidates): {len(witnesses)}")
with open(os.path.join(adir, "witnesses.json"), "w") as f:
json.dump(witnesses, f, indent=2)
# human agreement if sheets are filled
for annotator in ("A", "B"):
p = os.path.join(adir, f"human_{annotator}.csv")
if os.path.exists(p):
h = pd.read_csv(p).fillna("")
filled = h[h["maux_codes"].astype(str).str.strip() != ""]
if len(filled) > 10:
keys = [k for k in filled["key"] if k in judge]
hs = [frozenset(str(r).replace(";", ",").split(","))
for r in filled.set_index("key").loc[keys, "maux_codes"]]
js = [judge[k][0] for k in keys]
for code in ["F1", "F4", "F7"]:
print(f"kappa(judge, {annotator}) {code}: "
f"{cohen_kappa(js, hs, code):.2f}")
def main() -> None:
ap = argparse.ArgumentParser()
sub = ap.add_subparsers(dest="cmd", required=True)
for name in ("sample", "judge", "report"):
p = sub.add_parser(name)
p.add_argument("--run-id", required=True)
p.add_argument("--results-dir", default="results")
p.add_argument("--config", default="config/experiment.yaml")
if name == "sample":
p.add_argument("--n", type=int, default=600)
p.add_argument("--dual", type=int, default=150)
args = ap.parse_args()
{"sample": cmd_sample, "judge": cmd_judge, "report": cmd_report}[args.cmd](args)
if __name__ == "__main__":
main()