{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Laya Formatting Fragility — runnable demo\n", "\n", "Small decision models (\"decide, don't chat\" — [Laya](https://huggingface.co/convaiinnovations/laya) and friends) return typed answers with probabilities in milliseconds. But their answers are **sensitive to formatting**: option key names, option order, and state phrasing change results while the situation and gold label stay identical.\n", "\n", "This notebook runs the 480-row perturbation suite end to end and prints the metrics table. Every row pair differs in exactly one formatting axis with the same gold label — any model answering differently is driven by format, not meaning.\n", "\n", "Dataset: https://huggingface.co/datasets/pranaysuyash/laya-formatting-fragility" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!pip -q install laya\n", "\n", "import json, urllib.request\n", "from pathlib import Path\n", "\n", "URL = \"https://huggingface.co/datasets/pranaysuyash/laya-formatting-fragility/resolve/main/data/fragility_test.jsonl\"\n", "DATA = Path(\"fragility_test.jsonl\")\n", "if not DATA.exists():\n", " urllib.request.urlretrieve(URL, DATA)\n", "rows = [json.loads(l) for l in DATA.read_text().splitlines() if l.strip()]\n", "print(f\"{len(rows)} rows loaded\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import laya\n", "\n", "agent = laya.load(\"convaiinnovations/laya\") # ~800 MB download on first run\n", "\n", "def predict(state, questions_json):\n", " a = agent.predict(state, json.loads(questions_json))[\"answers\"][\"target\"]\n", " if a.get(\"choice\") is not None:\n", " return a[\"choice\"], a.get(\"confidence\")\n", " if a.get(\"score\") is not None:\n", " probs = a.get(\"probabilities\") or {}\n", " return (max(probs, key=probs.get) if probs else None), a.get(\"confidence\")\n", " n = a.get(\"noul\")\n", " return (str(n is not None and n >= 0.5).lower()), a.get(\"confidence\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import statistics\n", "from collections import defaultdict\n", "\n", "def matches(ans, row):\n", " gold = json.loads(row[\"gold\"])\n", " if row[\"task_type\"] == \"score\" and ans not in gold[\"options\"]:\n", " try:\n", " idx = min(range(len(gold[\"options\"])), key=lambda j: abs(float(ans) - j))\n", " return gold[\"options\"][idx] == gold[\"label\"]\n", " except (TypeError, ValueError):\n", " return False\n", " return ans == gold[\"label\"]\n", "\n", "results = []\n", "for row in rows:\n", " ans, conf = predict(row[\"state\"], row[\"questions\"])\n", " results.append({\"row\": row, \"answer\": ans, \"confidence\": conf, \"correct\": matches(ans, row)})\n", "\n", "def acc(preds):\n", " return round(sum(p[\"correct\"] for p in preds) / len(preds), 3) if preds else float(\"nan\")\n", "\n", "def slice_of(axis, value):\n", " return acc([r for r in results if r[\"row\"][axis] == value])\n", "\n", "def flip_rate(axis, a, b):\n", " groups = defaultdict(dict)\n", " for r in results:\n", " row = r[\"row\"]\n", " key = (row[\"base_id\"],\n", " row[\"phrasing\"] if axis != \"phrasing\" else None,\n", " row[\"order\"] if axis != \"order\" else None,\n", " row[\"key_variant\"] if axis != \"key_variant\" else None)\n", " slot = row[axis] if row[axis] in (a, b) else None\n", " if slot is not None:\n", " groups[key][slot] = r\n", " pairs = [v for v in groups.values() if len(v) == 2]\n", " return round(sum(1 for p in pairs if p[a][\"answer\"] != p[b][\"answer\"]) / len(pairs), 3) if pairs else None\n", "\n", "report = {\n", " \"overall_accuracy\": acc(results),\n", " \"baseline_accuracy\": acc([r for r in results if r[\"row\"][\"phrasing\"] == \"p0\"\n", " and r[\"row\"][\"order\"] == \"forward\"\n", " and r[\"row\"][\"key_variant\"] in (\"semantic\", \"q0\")]),\n", " \"accuracy_by_phrasing\": {p: slice_of(\"phrasing\", p) for p in (\"p0\", \"p1\", \"p2\")},\n", " \"accuracy_by_order\": {o: slice_of(\"order\", o) for o in (\"forward\", \"reversed\")},\n", " \"accuracy_by_keys\": {v: slice_of(\"key_variant\", v)\n", " for v in sorted({r[\"row\"][\"key_variant\"] for r in results})},\n", " \"flip_rate\": {\n", " \"keys_semantic_vs_abstract\": flip_rate(\"key_variant\", \"semantic\", \"abstract\"),\n", " \"order_forward_vs_reversed\": flip_rate(\"order\", \"forward\", \"reversed\"),\n", " \"phrasing_p0_vs_p1\": flip_rate(\"phrasing\", \"p0\", \"p1\"),\n", " },\n", "}\n", "ok = [r[\"confidence\"] for r in results if r[\"correct\"] and r[\"confidence\"] is not None]\n", "err = [r[\"confidence\"] for r in results if not r[\"correct\"] and r[\"confidence\"] is not None]\n", "report[\"confidence\"] = {\"mean_on_correct\": round(statistics.mean(ok), 3),\n", " \"mean_on_incorrect\": round(statistics.mean(err), 3)}\n", "print(json.dumps(report, indent=2))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Reading the output\n", "\n", "- **flip_rate** is the headline: for pairs of rows that are identical except for one formatting axis, how often does the model's answer change? Reference values for laya 0.3.5: keys 0.872, order 0.217, phrasing 0.150.\n", "- **confidence** separating correct from incorrect means a confidence gate is usable *on this kind of data*; on out-of-domain jargon it has been measured flat — test per domain before gating.\n", "- To benchmark a different typed-decision engine on identical rows, implement its `predict(state, questions_json)` adapter (see `probe_harness.py` in the dataset).\n", "\n", "Apache-2.0. Full writeup: https://huggingface.co/datasets/pranaysuyash/laya-formatting-fragility" ] } ], "metadata": { "kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"}, "language_info": {"name": "python", "version": "3.12"} }, "nbformat": 4, "nbformat_minor": 5 }