#!/usr/bin/env python3 """Probe harness for the laya-formatting-fragility dataset. Runs a decision model over every row and reports, per perturbation axis: - accuracy at the baseline slice vs each perturbed slice - answer-flip rate between otherwise-identical rows - confidence on correct vs incorrect answers Adapter interface: implement `predict(state, questions_json) -> (answer, confidence)` for your decision model. The Laya adapter is implemented; the Jev (or any hosted) adapter is left as a documented stub so results are comparable across engines. Usage: python probe_harness.py --data data/fragility_test.jsonl [--model laya] """ from __future__ import annotations import argparse import json import statistics from collections import defaultdict from pathlib import Path # ---------------------------------------------------------------- adapters def laya_predict(state: str, questions_json: str) -> tuple[str | None, float | None]: import laya # deferred: heavy import global _LAYA_AGENT try: agent = _LAYA_AGENT except NameError: _LAYA_AGENT = agent = laya.load("convaiinnovations/laya") result = agent.predict(state, json.loads(questions_json)) answer = result["answers"]["target"] if answer.get("choice") is not None: return answer.get("choice"), answer.get("confidence") if answer.get("score") is not None: # score rows: snap expected level to the nearest named level via argmax probs = answer.get("probabilities") or {} best = max(probs, key=lambda k: probs.get(k, 0.0)) if probs else None return best, answer.get("confidence") noul = answer.get("noul") return (str(noul is not None and noul >= 0.5).lower(), answer.get("confidence")) def jev_predict(state: str, questions_json: str) -> tuple[str | None, float | None]: raise NotImplementedError( "Hosted-adapter stub: POST {state, questions} to your Jev endpoint, " "map answers.target.{choice|score|noul} + confidence, and compare. " "Implemented locally per deployment; do not commit credentials." ) ADAPTERS = {"laya": laya_predict, "jev": jev_predict} # ---------------------------------------------------------------- scoring def label_of(row: dict) -> str: return json.loads(row["gold"])["label"] def row_matches(answer: str | None, row: dict) -> bool: gold = json.loads(row["gold"]) if row["task_type"] == "score": gold_opts = gold["options"] if answer in gold_opts: return answer == gold["label"] # index answers refer to the row's OWN criteria order (reversed rows # reorder the list); map through it, never through gold["options"] try: row_criteria = json.loads(row["questions"])["target"]["criteria"] idx = int(round(float(answer))) if 0 <= idx < len(row_criteria): return row_criteria[idx] == gold["label"] return False except (TypeError, ValueError): return False return answer == gold["label"] def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--data", type=Path, default=Path(__file__).parent / "data" / "fragility_test.jsonl") parser.add_argument("--model", choices=sorted(ADAPTERS), default="laya") args = parser.parse_args() predict = ADAPTERS[args.model] rows = [json.loads(line) for line in args.data.read_text(encoding="utf-8").splitlines() if line.strip()] results = [] for row in rows: answer, confidence = predict(row["state"], row["questions"]) if row["task_type"] == "score": # resolve level indices to names via the row's OWN criteria order # (reversed rows reorder the list) so pair comparisons are # content-based, not position-based try: row_criteria = json.loads(row["questions"])["target"]["criteria"] idx = int(round(float(answer))) if 0 <= idx < len(row_criteria): answer = row_criteria[idx] except (TypeError, ValueError): pass results.append({ "row": row, "answer": answer, "confidence": confidence, "correct": row_matches(answer, row), }) def acc(preds: list[dict]) -> float: return sum(p["correct"] for p in preds) / len(preds) if preds else float("nan") def slice_of(axis: str, value: str) -> list[dict]: return [r for r in results if r["row"][axis] == value] report: dict = {"model": args.model, "rows": len(results), "overall_accuracy": round(acc(results), 3)} # per-axis slices (each axis at its baseline values for the others) baseline = [r for r in results if r["row"]["phrasing"] == "p0" and r["row"]["order"] == "forward" and r["row"]["key_variant"] in ("semantic", "q0")] report["baseline_accuracy"] = round(acc(baseline), 3) report["by_phrasing"] = {p: round(acc(slice_of("phrasing", p)), 3) for p in ("p0", "p1", "p2")} report["by_order"] = {o: round(acc(slice_of("order", o)), 3) for o in ("forward", "reversed")} report["by_key_variant"] = { v: round(acc([r for r in results if r["row"]["key_variant"] == v]), 3) for v in sorted({r["row"]["key_variant"] for r in results}) } # flip rates: pairs identical except one axis. The key axis compares # answer POSITIONS within each row's own criteria (semantic names and # abstract aliases are different label spaces; positions are canonical). def answer_position(r: dict) -> int | None: row_criteria = json.loads(r["row"]["questions"])["target"]["criteria"] if isinstance(row_criteria, dict): row_criteria = list(row_criteria.keys()) try: return row_criteria.index(r["answer"]) except ValueError: return None def flip(axis: str, value_a: str, value_b: str) -> float | None: by_base = defaultdict(dict) for r in results: row = r["row"] key = (row["base_id"], row["phrasing"] if axis != "phrasing" else None, row["order"] if axis != "order" else None, row["key_variant"] if axis != "key_variant" else None) slot = value_a if row[axis] == value_a else value_b if row[axis] == value_b else None if slot is not None: by_base[key][slot] = r pairs = [(v.get(value_a), v.get(value_b)) for v in by_base.values() if len(v) == 2] if not pairs: return None if axis == "key_variant": flips = sum(1 for a, b in pairs if answer_position(a) != answer_position(b)) else: flips = sum(1 for a, b in pairs if a["answer"] != b["answer"]) return round(flips / len(pairs), 3) report["flip_rate"] = { "phrasing_p0_vs_p1": flip("phrasing", "p0", "p1"), "order_forward_vs_reversed": flip("order", "forward", "reversed"), "keys_semantic_vs_abstract": flip("key_variant", "semantic", "abstract"), } conf_ok = [r["confidence"] for r in results if r["correct"] and r["confidence"] is not None] conf_err = [r["confidence"] for r in results if not r["correct"] and r["confidence"] is not None] report["confidence"] = { "mean_on_correct": round(statistics.mean(conf_ok), 3) if conf_ok else None, "mean_on_incorrect": round(statistics.mean(conf_err), 3) if conf_err else None, "separates_errors": ( bool(conf_ok and conf_err) and statistics.mean(conf_ok) - statistics.mean(conf_err) > 0.1 ), } print(json.dumps(report, indent=2)) out = Path(__file__).parent / "reports" / f"fragility_{args.model}.json" out.parent.mkdir(parents=True, exist_ok=True) out.write_text(json.dumps(report, indent=2)) return 0 if __name__ == "__main__": raise SystemExit(main())