Non-autoregressive System 1 decision engine. Typed choice, score and yes/no decisions over any text in a single forward pass, in 100+ languages, with a router that picks the right checkpoint per request.
Python calibrationclassificationdecision-modelhuggingfacejevmodernbertmultilingualnlppythonpytorchroutingtyped-decisionszero-shot
fix(hooks): align stability calibration and replay precision
xp8257e91e4c8c
diff --git a/docs/hooks/api.md b/docs/hooks/api.mdindex 39805925..b68a6085 100644--- a/docs/hooks/api.md+++ b/docs/hooks/api.md@@ -164,7 +164,7 @@ Thresholds `accept` and `escalate` are required keyword arguments: categorical gIt attaches a `reliability` diagnostic block to each choice question's answer:- `probes`: List of probe kinds that executed (e.g. `["rename"]`, `["reorder", "rename"]`, or `[]`).- `option_layout`: Checkpoint layout (`"parallel"` or `"sequential"`).-- `soft_stability`: Mean probability assigned to the chosen option across all evaluated variants (`None` if unprobed).+- `soft_stability`: Mean probability assigned to the chosen option across all evaluated variants, without additional rounding (`None` if unprobed). This is the exact value used for `decision`.- `stability`: Fraction of variants whose argmax choice agrees with the original decision (`None` if unprobed).- `rename_stability`: Stability across rename variants (`None` if no rename probe ran).- `reorder_stability`: Stability across reorder variants (`None` if no reorder probe ran).@@ -172,6 +172,29 @@ It attaches a `reliability` diagnostic block to each choice question's answer:- `variant_choices`: Mapping of variant name to decoded choice.- `variant_support`: Mapping of variant name to probability mass on the primary choice.+### Calibrating and replaying decisions++Collect `soft_stability` with `accept=None, escalate=None` on labelled evaluation examples,+then pass those numeric values and correctness labels to `laya.hooks.calibrate_reliability`.+Only fit or replay probed, numeric scores; exclude unprobed reports with `soft_stability=None`+and keep their `decision=None`.+It chooses cutoffs from the distinct input scores at their supplied precision; equal scores+stay in the same group. `ACCEPT` includes scores equal to `accept`, while `ESCALATE` requires+a score strictly below `escalate`. If no cutoff meets the requested accuracy, `accept=1.01`+accepts nothing. These are fits to the supplied examples, not a guarantee on unseen data.++Keep the numeric scores and thresholds unchanged when saving them (for example, in JSON).+Replaying `decide_reliability(report["soft_stability"], accept, escalate)` then agrees with+the hook for the same evaluated variants and decoded probabilities. Format a separate display+string if fewer decimal places are wanted; do not fit or gate on that string. The other stability+diagnostics and `variant_support` retain their four-decimal formatting and are not substitutes+for `soft_stability` when replaying the gate.++Earlier reports rounded `soft_stability` to four decimals even though the gate used the+unrounded mean. Previously saved reports cannot recover that lost precision: recollect them+before refitting thresholds. Fixed thresholds still use the same runtime comparison; the+reported score and newly fitted cutoffs may now contain more decimal places.+### What it costsOne forward pass, not several, but a wider one: the variants are extra rows in the same batch.diff --git a/laya/hooks.py b/laya/hooks.pyindex 5bcce251..8ae4047c 100644--- a/laya/hooks.py+++ b/laya/hooks.py@@ -655,11 +655,13 @@ def calibrate_reliability(escalate = highest cutoff below `accept` where answers below it are at most`max_escalate_accuracy` accurate.If no cutoff reaches `target_accuracy`, accept is returned as 1.01 (accept nothing).+ Cutoffs use the supplied scores without rounding, matching the hook's reported+ `soft_stability` and runtime comparison. Equal scores are evaluated together."""pairs = sorted(zip(soft_scores, correct))if not pairs:raise ValueError("cannot calibrate reliability on empty scores/correct pairs")- cuts = sorted({round(s, 4) for s, _ in pairs})+ cuts = sorted({s for s, _ in pairs})accept = 1.01for t in cuts:@@ -1002,7 +1004,7 @@ class OptionStabilityHook(BaseHook):"probes": list(probes_ran),"option_layout": layout,"decision": decide_reliability(soft, self.accept, self.escalate) if soft is not None else None,- "soft_stability": round(soft, 4) if soft is not None else None,+ "soft_stability": soft,"stability": round(stability, 4) if stability is not None else None,"rename_stability": round(rename_stab, 4) if rename_stab is not None else None,"reorder_stability": round(reorder_stab, 4) if reorder_stab is not None else None,diff --git a/tests/test_hooks_api.py b/tests/test_hooks_api.pyindex 1a5840d9..5e15e447 100644--- a/tests/test_hooks_api.py+++ b/tests/test_hooks_api.py@@ -24,7 +24,7 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))import laya # noqa: E402from laya import Agent, AsyncHook, BaseHook, OptionStabilityHook, PredictContext, PredictHook, Router, load # noqa: E402-from laya.hooks import HOOK_EVENTS, Hook # noqa: E402+from laya.hooks import HOOK_EVENTS, Hook, calibrate_reliability, decide_reliability # noqa: E402from laya.onnx_agent import ONNXAgent # noqa: E402from laya.router import _question_schema # noqa: E402@@ -172,6 +172,16 @@ check_param("AsyncHook.__init__", AsyncHook.__init__, "loop", None)# OptionStabilityHook (issue #635)check_true("OptionStabilityHook is a BaseHook", issubclass(OptionStabilityHook, BaseHook))+# Public calibration cuts retain input precision through JSON serialization. Replaying+# the cuts must not merge distinct scores that happen to share a four-place display.+_precise_scores = json.loads(json.dumps([0.80001, 0.80002]))+_precise_cuts = calibrate_reliability(_precise_scores, [False, True], target_accuracy=1.0)+_precise_cuts = json.loads(json.dumps(_precise_cuts))+check("calibrate_reliability returns an observed full-precision cut", _precise_cuts[0], 0.80002)+check("serialized calibration cuts preserve accepted membership",+ [decide_reliability(score, *_precise_cuts) for score in _precise_scores],+ ["VERIFY", "ACCEPT"])+# --------------------------------------------------------------- predict surfacesfrom laya.mcp.remote import RemoteRouter # noqa: E402diff --git a/tests/test_option_stability.py b/tests/test_option_stability.pyindex 784a14a6..7580bef8 100644--- a/tests/test_option_stability.py+++ b/tests/test_option_stability.py@@ -4,6 +4,7 @@ Pure Python tests: runs offline without torch or checkpoint downloads.Run: python tests/test_option_stability.py"""+import jsonimport osimport sys@@ -375,6 +376,86 @@ with _test_warnings.catch_warnings(record=True) as _warn_records:check_true("normalization/bogus emits warning", any("unknown option_layout" in str(w.message) for w in _warn_records))+# --------------------------------------------------------------- calibration precision and replay+def precision_report(supports, accept=None, escalate=None):+ """Use real hook aggregation over simulated per-variant model probabilities."""+ precision_hook = OptionStabilityHook(accept=accept, escalate=escalate, variants="fast")+ precision_ctx = PredictContext(states=["Keep the request"], questions={+ "action": {"type": "choice", "instructions": "Which action?",+ "criteria": {"keep": "keep request", "defer": "defer request"}},+ })+ precision_hook.on_predict_start(precision_ctx)+ assert len(precision_ctx.questions) == len(supports) == 3+ answers = {}+ for (qid, question), support in zip(precision_ctx.questions.items(), supports):+ target = next(k for k, value in question["criteria"].items() if value == "keep request")+ other = next(k for k in question["criteria"] if k != target)+ answers[qid] = {"type": "choice", "choice": target if support >= 0.5 else other,+ "probabilities": {target: support, other: 1.0 - support}}+ precision_ctx.results = [{"answers": answers, "usage": {}}]+ precision_hook.on_predict_end(precision_ctx)+ return precision_ctx.results[0]["answers"]["action"]["reliability"]+++# The individual probabilities have four decimal places; their mean generally does not.+# A saved report must reproduce the live decision without changing caller-supplied cuts.+for name, supports, accept, escalate, expected in (+ ("accept round-up", [0.7999, 0.8, 0.8], 0.8, 0.6, "VERIFY"),+ ("escalate round-up", [0.5999, 0.6, 0.6], 0.8, 0.6, "ESCALATE"),+ ("precise caller cut", [0.8001, 0.8, 0.8], 0.80002, 0.6, "ACCEPT"),+ ("uncalibrated", [0.7999, 0.8, 0.8], None, None, None),+):+ report = precision_report(supports, accept, escalate)+ restored = json.loads(json.dumps(report))+ check("precision/%s live decision" % name, report["decision"], expected)+ check("precision/%s reports the gated mean" % name, report["soft_stability"], sum(supports) / 3)+ check("precision/%s JSON replay" % name,+ decide_reliability(restored["soft_stability"], accept, escalate), expected)++# Fit from persisted reports, then replay the exact same model outputs. The lower two+# scores round to the same four-place value, but each is a distinct possible cutoff.+calibration_supports = [+ [0.8, 0.6, 0.7],+ [0.8, 0.6, 0.7001],+ [0.8, 0.6, 0.7002],+]+saved_reports = json.loads(json.dumps([precision_report(row) for row in calibration_supports]))+saved_scores = [report["soft_stability"] for report in saved_reports]+fitted = calibrate_reliability(saved_scores, [False, False, True],+ target_accuracy=1.0, max_escalate_accuracy=0.0)+fitted = json.loads(json.dumps(fitted))+check("precision/fitted accept is the observed upper mean", fitted[0], sum(calibration_supports[2]) / 3)+check("precision/fitted escalate is the observed middle mean", fitted[1], sum(calibration_supports[1]) / 3)+check("precision/JSON fit and hook replay preserve all three bands",+ [precision_report(row, *fitted)["decision"] for row in calibration_supports],+ ["ESCALATE", "VERIFY", "ACCEPT"])+check("precision/escalate boundary is exclusive",+ decide_reliability(fitted[1], *fitted), "VERIFY")+check("precision/accept boundary is inclusive",+ decide_reliability(fitted[0], *fitted), "ACCEPT")++# Rounding a sole candidate up can leave no retained row; rounding nearby candidates+# down can merge a wrong row into a group that has a valid perfect-accuracy cutoff.+for name, values, labels, expected_cut in (+ ("round-up retains a lone correct row", [0.80006], [True], 0.80006),+ ("round-down keeps nearby scores separable", [0.80001, 0.80002], [False, True], 0.80002),+):+ accept, escalate = calibrate_reliability(values, labels, target_accuracy=1.0)+ check("precision/calibrate %s" % name, accept, expected_cut)+ accepted = [ok for value, ok in zip(values, labels)+ if decide_reliability(value, accept, escalate) == "ACCEPT"]+ check("precision/calibrate %s retained group" % name, accepted, [True])++check("precision/exact ties cannot be split",+ calibrate_reliability([0.8, 0.8], [False, True], target_accuracy=1.0), (1.01, 0.0))+check("precision/duplicate scores enter as a whole group",+ calibrate_reliability([0.8, 0.8], [False, True], target_accuracy=0.5), (0.8, 0.0))+check("precision/zero and one retain their boundary cuts",+ calibrate_reliability([0.0, 1.0], [False, True], target_accuracy=1.0), (1.0, 0.0))+check("precision/zero is accepted at a zero cutoff", decide_reliability(0.0, 0.0, 0.0), "ACCEPT")+check("precision/sentinel accepts no probability", decide_reliability(1.0, 1.01, 0.0), "VERIFY")++# --------------------------------------------------------------- reportprint("\n%d passed, %d failed" % (len(PASS), len(FAIL)))for f in FAIL: