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
feat(onnx): add ONNXAgent.predict_batch, the batch API the torch Agent has (#323)
Aashish4b81bd754810
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 7a9cca5f..24391bbc 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -104,6 +104,7 @@ jobs:python tests/test_structured.pypython tests/test_structured_api.pypython tests/test_onnx_lang_parity.py+ python tests/test_onnx_batch.pypython tests/test_download.pypython tests/test_shortlist.pypython tests/test_decision_model.pydiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 8344b4ba..f9a0771a 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -43,6 +43,7 @@ jobs:python tests/test_batch.pypython tests/test_predict_long.pypython tests/test_onnx_lang_parity.py+ python tests/test_onnx_batch.pypython tests/test_email.pypython tests/test_download.pypython tests/test_shortlist.pydiff --git a/README.md b/README.mdindex 49387955..a756d76c 100644--- a/README.md+++ b/README.md@@ -560,6 +560,10 @@ batched (measured ~9–10×). On CPU, increasing batch size alone may not speedlength grouping can help by reducing the padded work in a mixed-length workload. See the[CPU measurements and reproduction commands](research/README.md#length-batching).+`ONNXAgent.predict_batch(states, questions, batch_size=...)` has the same contract, backed by one+ONNX Runtime session run per chunk, so an ONNX deployment gets the same batch API and the same+result shape; `sort_by_length` is not ported there yet.+### Long documents: `predict_long``predict`/`system_one` truncate a state that exceeds `max_len` to a single window (the first, ordiff --git a/laya/onnx_agent.py b/laya/onnx_agent.pyindex 7afa4bed..b2b459a0 100644--- a/laya/onnx_agent.py+++ b/laya/onnx_agent.py@@ -3,7 +3,7 @@ import osimport threadingimport timeimport warnings-from typing import Any, Dict, Optional, Union+from typing import Any, Dict, List, Optional, Unionimport numpy as np@@ -232,26 +232,106 @@ class ONNXAgent(HookRegistry):max_len: Optional[int] = None,head_max_len: Optional[int] = None,min_confidence: Optional[float] = None) -> Dict[str, Any]:- """Evaluate typed questions, running any opt-in hooks around the inference.+ """Evaluate typed questions across state in one ONNX Runtime session run.`lang` selects a per-language temperature override (see `lang_temperatures`), matching thePyTorch `Agent.system_one` signature so either backend is a drop-in for the other.++ Defined in terms of `predict_batch`, exactly as the PyTorch `Agent.system_one` is, so the+ single-state and batched paths cannot drift apart.++ Args:+ state: Text string, JSON dict, or conversation turn list.+ questions: Question definitions, with the shapes `Agent.system_one` accepts.+ lang: Per-language temperature override (see `lang_temperatures`).+ hooks (HookArg): Per-call hooks, appended after any installed on the agent.+ on_predict_start (PredictHookArg): A per-call start hook. It may rewrite the+ state/questions or call `ctx.skip(...)` to short-circuit inference.+ on_predict_end (PredictHookArg): A per-call end hook. It may rewrite the results.+ hooks_raise: Override the agent's `hooks_raise` for this call.+ hooks_timeout: Override the agent's `hooks_timeout` for this call.+ max_len: Override the config's `max_len` for this call.+ head_max_len: Override the config's `head_max_len` for this call.+ min_confidence: Opt-in abstention threshold on `answer_confidence` (#361); an answer+ below it is returned flagged with `low_confidence: True`.++ Returns:+ Dictionary with answers, probabilities, calibrated confidence, and token usage.++ To score many states at once, see `predict_batch`, which shares session runs across them.+ """+ return self.predict_batch([state], questions, lang=lang, hooks=hooks,+ on_predict_start=on_predict_start,+ on_predict_end=on_predict_end, hooks_raise=hooks_raise,+ hooks_timeout=hooks_timeout,+ max_len=max_len, head_max_len=head_max_len,+ min_confidence=min_confidence)[0]++ def predict_batch(self, states: List[Union[str, dict, list]], questions: Dict[str, Dict[str, Any]],+ batch_size: Optional[int] = None, lang: Optional[str] = None,+ hooks=None, on_predict_start=None, on_predict_end=None,+ hooks_raise: Optional[bool] = None,+ hooks_timeout: Optional[float] = None,+ max_len: Optional[int] = None,+ head_max_len: Optional[int] = None,+ min_confidence: Optional[float] = None) -> List[Dict[str, Any]]:+ """Evaluate the same questions over many states, sharing ONNX Runtime session runs.++ The throughput path, mirroring `laya.agent.Agent.predict_batch`: `system_one` collates one+ state's question rows per session run, so N states cost N runs. `predict_batch` collates+ several states' rows into one run -- or `ceil(len(states) / batch_size)` of them -- which is+ where ONNX Runtime's own parallelism pays off on CPU.++ Args:+ states: A list of states (each a text string, JSON dict, or conversation turn list).+ The same `questions` are evaluated against every state.+ questions: Question definitions, exactly as accepted by `system_one`.+ batch_size: Optional cap on states per session run. `None` sends them all in one run;+ set it to bound peak memory when batching many or long states.+ lang: Per-language temperature override applied to every state; see+ `lang_temperatures`.+ hooks (HookArg): Per-call hooks, appended after any installed on the agent.+ on_predict_start (PredictHookArg): A per-call start hook. It may rewrite the+ states/questions or call `ctx.skip(...)` to short-circuit inference.+ on_predict_end (PredictHookArg): A per-call end hook. It may rewrite the results.+ hooks_raise: Override the agent's `hooks_raise` for this call.+ hooks_timeout: Override the agent's `hooks_timeout` for this call.+ max_len: Override the config's `max_len` for this call.+ head_max_len: Override the config's `head_max_len` for this call.+ min_confidence: Opt-in abstention threshold on `answer_confidence` (#361); answers+ below it are returned flagged with `low_confidence: True`.++ Returns:+ A list of per-state result dicts, each identical in shape to `system_one`'s output and+ aligned with `states` by index."""mc = check_min_confidence(min_confidence) if min_confidence is not None else Noneactive = compose_hooks(self.hooks, hooks, on_predict_start, on_predict_end)raise_errors = self.hooks_raise if hooks_raise is None else bool(hooks_raise)timeout = self.hooks_timeout if hooks_timeout is None else validate_timeout(hooks_timeout)- ctx = PredictContext(states=[state], questions=questions, model=self.model_id, agent=self,+ ctx = PredictContext(states=states, questions=questions, model=self.model_id, agent=self,max_len=max_len, head_max_len=head_max_len)try:dispatch(active, "on_predict_start", ctx, raise_errors=raise_errors, lock=self._hooks_lock, timeout=timeout)+ states, questions = ctx.states, ctx.questionsif ctx.results is None:- overrides = {}- if ctx.max_len is not None:- overrides["max_len"] = ctx.max_len- if ctx.head_max_len is not None:- overrides["head_max_len"] = ctx.head_max_len- ctx.results = [self._infer(ctx.states[0], ctx.questions, lang=lang, **overrides)]+ # A start hook may have normalised a bare string/dict into a list; only the value+ # that survives the hook is validated, as Agent.predict_batch does.+ if isinstance(states, (str, bytes, dict)):+ raise TypeError(+ "predict_batch expects a list of states; pass a single state to predict()/system_one()."+ )+ states = list(states)+ if not states:+ ctx.results = []+ else:+ overrides: Dict[str, int] = {}+ if ctx.max_len is not None:+ overrides["max_len"] = ctx.max_len+ if ctx.head_max_len is not None:+ overrides["head_max_len"] = ctx.head_max_len+ ctx.results = self._infer_batch(states, questions, lang=lang,+ batch_size=batch_size, **overrides)except BaseException as exc:ctx.error = exctry:@@ -272,38 +352,31 @@ class ONNXAgent(HookRegistry):ctx.error.__context__ = hook_excelse:raise- return ctx.results[0]+ return ctx.resultsdef _infer(self, state: Union[str, dict, list], questions: Dict[str, Dict[str, Any]],max_len: Optional[int] = None, head_max_len: Optional[int] = None,lang: Optional[str] = None) -> Dict[str, Any]:- from .agent import Agent as _Agent-- ids = list(questions.keys())- if not ids:- return {- "model": "laya-rl-agent-onnx",- "answers": {},- "usage": {"input_tokens": 0, "output_tokens": 0},- }- for qid in ids:- _Agent._check_question(qid, questions[qid])- items = []- max_len = self.cfg.get("max_len", 512) if max_len is None else max_len- head_max_len = self.cfg.get("head_max_len", 192) if head_max_len is None else head_max_len+ """Answer one state without hooks: one session run, the `predict_batch([state])` case."""+ return self._infer_batch([state], questions, max_len=max_len, head_max_len=head_max_len,+ lang=lang)[0]+ def _encode_state(self, state: Union[str, dict, list], ids: List[str], internal: Dict[str, Any],+ max_len: int, head_max_len: int) -> List[Dict[str, Any]]:+ """This state's question rows, tokenizing the state once for all of them."""+ truncate_left = isinstance(state, list)# Tokenize the shared state once and reuse it across questions, instead of# re-serializing and re-tokenizing the same document inside build_sequence per# question (the PyTorch Agent already does this via `state_ids`).- truncate_left = isinstance(state, list)state_ids = encode_text(self.tok,serialize_state(state).replace(self.tok.mask_token, " "),add_special_tokens=False,)["input_ids"]+ items = []for qid in ids:- q = self._to_internal(questions[qid])+ q = internal[qid]seq, markers = build_sequence(self.tok, state, q, max_len, head_max_len,truncate_left=truncate_left, state_ids=state_ids,@@ -311,39 +384,22 @@ class ONNXAgent(HookRegistry):if len(markers) != len(render_options(q)):raise ValueError("question %r options exceed head_max_len=%d" % (qid, head_max_len))items.append({"ids": seq, "markers": markers, "qtype": QTYPES[q["t"]]})+ return items- b = collate_items([items], self.tok.pad_token_id)-- # Prepare ONNX inputs as numpy arrays- ort_inputs = {- "input_ids": b["input_ids"].numpy().astype(np.int64),- "attention_mask": b["attention_mask"].numpy().astype(np.int64),- "marker_pos": b["marker_pos"].numpy().astype(np.int64),- "marker_mask": b["marker_mask"].numpy().astype(bool),- "qtype": b["qtype"].numpy().astype(np.int64),- }-- # Run ONNX inference- ort_outs = self.session.run(["logits", "act_logits"], ort_inputs)- logits = ort_outs[0]- act_logits = ort_outs[1]-- # Compute softmax for actions manually in numpy- act_exp = np.exp(act_logits - np.max(act_logits, axis=-1, keepdims=True))- act = act_exp / np.sum(act_exp, axis=-1, keepdims=True)-+ def _decode_answers(self, logits, act, items: List[Dict[str, Any]], ids: List[str],+ internal: Dict[str, Any], offset: int,+ lang: Optional[str] = None) -> Dict[str, Any]:+ """Decode the `len(ids)` head rows starting at `offset` into this state's answers."""answers = {}- n_tokens = int(b["attention_mask"].sum())-for r, qid in enumerate(ids):- q = self._to_internal(questions[qid])+ q = internal[qid]k = len(items[r]["markers"])qt = QTYPES[q["t"]]t_scale = self.temperature_by_options.get(temp_bucket(qt, k), self.temperature[qt])if lang and lang.split("-")[0].lower() in self.lang_temperatures:l_cfg = self.lang_temperatures[lang.split("-")[0].lower()]t_scale = l_cfg["temperature_by_options"].get(temp_bucket(qt, k), l_cfg["temperature"][qt])- z = logits[r, :k] / t_scale+ z = logits[offset + r, :k] / t_scalep = np.exp(z - z.max())p = p / p.sum()@@ -352,7 +408,7 @@ class ONNXAgent(HookRegistry):# type so a caller can gate across types on one number -- matching the PyTorch Agent,# whose output ONNX callers otherwise cannot read (KeyError on cross-backend swap).ans_conf = round(answer_confidence(p, k), 4)- ext = {"act_probability": round(float(act[r, 0]), 4)}+ ext = {"act_probability": round(float(act[offset + r, 0]), 4)}if q["t"] == "choice":keys = list(q["crit"].keys())@@ -383,12 +439,63 @@ class ONNXAgent(HookRegistry):"answer_confidence": ans_conf,"action": ext,}+ return answers++ def _infer_batch(self, states: List[Union[str, dict, list]], questions: Dict[str, Dict[str, Any]],+ max_len: Optional[int] = None, head_max_len: Optional[int] = None,+ lang: Optional[str] = None,+ batch_size: Optional[int] = None) -> List[Dict[str, Any]]:+ """Validate once, then encode, collate, run and decode in chunks of `batch_size` states."""+ from .agent import Agent as _Agent++ ids = list(questions.keys())+ if not ids:+ return [{"model": "laya-rl-agent-onnx", "answers": {},+ "usage": {"input_tokens": 0, "output_tokens": 0}} for _ in states]+ for qid in ids:+ _Agent._check_question(qid, questions[qid])+ internal = {qid: self._to_internal(questions[qid]) for qid in ids}+ max_len = self.cfg.get("max_len", 512) if max_len is None else max_len+ head_max_len = self.cfg.get("head_max_len", 192) if head_max_len is None else head_max_len+ chunk = batch_size if (batch_size and batch_size > 0) else len(states)++ results: List[Dict[str, Any]] = []+ for start in range(0, len(states), chunk):+ part = states[start:start + chunk]+ encoded = [self._encode_state(st, ids, internal, max_len, head_max_len) for st in part]++ b = collate_items(encoded, self.tok.pad_token_id)++ # Prepare ONNX inputs as numpy arrays+ ort_inputs = {+ "input_ids": b["input_ids"].numpy().astype(np.int64),+ "attention_mask": b["attention_mask"].numpy().astype(np.int64),+ "marker_pos": b["marker_pos"].numpy().astype(np.int64),+ "marker_mask": b["marker_mask"].numpy().astype(bool),+ "qtype": b["qtype"].numpy().astype(np.int64),+ }- return {- "model": "laya-rl-agent-onnx",- "answers": answers,- "usage": {"input_tokens": n_tokens, "output_tokens": 0},- }+ # Run ONNX inference+ ort_outs = self.session.run(["logits", "act_logits"], ort_inputs)+ logits = ort_outs[0]+ act_logits = ort_outs[1]++ # Compute softmax for actions manually in numpy+ act_exp = np.exp(act_logits - np.max(act_logits, axis=-1, keepdims=True))+ act = act_exp / np.sum(act_exp, axis=-1, keepdims=True)+ att = b["attention_mask"]++ row = 0+ for index, items in enumerate(encoded):+ nrows = len(items)+ n_tokens = int(att[row:row + nrows].sum())+ results.append({+ "model": "laya-rl-agent-onnx",+ "answers": self._decode_answers(logits, act, items, ids, internal, row, lang=lang),+ "usage": {"input_tokens": n_tokens, "output_tokens": 0},+ })+ row += nrows+ return resultsdef decide(self, state: Union[str, dict, list], schema: Any = None, *,questions: Optional[Dict[str, Dict[str, Any]]] = None, return_details: bool = False,diff --git a/tests/test_hooks.py b/tests/test_hooks.pyindex 755e69d1..14a0f249 100644--- a/tests/test_hooks.py+++ b/tests/test_hooks.py@@ -866,8 +866,16 @@ from laya.onnx_agent import ONNXAgent # noqa: E402o = ONNXAgent.__new__(ONNXAgent)o.model_id = "convaiinnovations/laya-onnx"-o._infer = lambda state, questions, **kwargs: {"model": "onnx", "answers": {},- "usage": {"input_tokens": 0, "output_tokens": 0}}+++def _fake_onnx_batch(states, questions, **kwargs):+ # `system_one` runs through `predict_batch` -> `_infer_batch`, as `Agent.system_one` does,+ # so the batch seam is what a hook test stubs.+ return [{"model": "onnx", "answers": {},+ "usage": {"input_tokens": 0, "output_tokens": 0}} for _ in states]+++o._infer_batch = _fake_onnx_batchonnx_seen = []onnx_models = []onnx_out = o.system_one("s", QUESTIONS,@@ -884,7 +892,7 @@ def _never(*args, **kwargs):raise AssertionError("inference should have been skipped")-o._infer = _never+o._infer_batch = _nevercheck("onnx/skip short-circuits",o.system_one("s", QUESTIONS, on_predict_start=lambda c: c.skip([{"model": "cached"}])),{"model": "cached"})diff --git a/tests/test_onnx_batch.py b/tests/test_onnx_batch.pynew file mode 100644index 00000000..9973c498--- /dev/null+++ b/tests/test_onnx_batch.py@@ -0,0 +1,298 @@+"""ONNXAgent.predict_batch: the batch path the PyTorch Agent has and ONNX did not (#323).++`Router.predict_batch` calls `agent.predict_batch` unconditionally, so an ONNX-backed Router raised+`AttributeError` on the batched entry point while the single-state path worked. Beyond the missing+method, one session run per state is the slow way to score many states: ONNX Runtime already+parallelises inside a run, so the rows of several states belong in one call.++No onnxruntime and no checkpoint: onnxruntime is imported lazily inside `__init__`, so the class+imports, and `predict_batch` is driven with a stub session and a fake tokenizer (the technique+`tests/test_onnx_lang_parity.py` uses for `_infer`). The stub derives each row's logits from that+row's own tokens, so a row decoded for the wrong state changes the answer and fails these checks.++Run: python tests/test_onnx_batch.py+"""+import inspect+import os+import sys+import threading++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++import numpy as np # noqa: E402++from laya.agent import Agent # noqa: E402+from laya.common import clamp_temperature # noqa: E402+from laya.onnx_agent import ONNXAgent # noqa: E402+from laya.router import Router # noqa: E402++PASS, FAIL = [], []+++def check(name, got, want):+ if got == want:+ PASS.append(name)+ else:+ FAIL.append("%s:\n got %r\n want %r" % (name, got, want))+++def check_true(name, cond, detail=""):+ if cond:+ PASS.append(name)+ else:+ FAIL.append("%s %s" % (name, detail))+++def check_raises(name, exc, fn):+ try:+ fn()+ except exc:+ PASS.append(name)+ except Exception as e: # noqa: BLE001+ FAIL.append("%s: raised %r, expected %s" % (name, e, exc.__name__))+ else:+ FAIL.append("%s: did not raise %s" % (name, exc.__name__))+++# ---------------------------------------------------------------- a fake tokenizer + stub session+class _FakeTok:+ cls_token_id, sep_token_id, mask_token_id, pad_token_id = 1, 2, 3, 0+ mask_token = "[M]"++ def __call__(self, text, add_special_tokens=False, truncation=False, max_length=None):+ ids = [10 + (ord(c) % 40) for c in text]+ if truncation and max_length:+ ids = ids[:max_length]+ return {"input_ids": ids}+++class _StubSession:+ """Row logits derived from the row's own tokens: a mis-mapped row changes the answer."""++ def __init__(self):+ self.calls = [] # rows per session run, in order++ def run(self, names, inputs):+ ids = inputs["input_ids"]+ self.calls.append(len(ids))+ # Every row for a state carries that state's tokens last, so this weight is constant+ # within a state and distinct across the states used below.+ weight = 1.0 + (ids.sum(axis=1) % 4)+ logits = np.stack([weight, np.ones_like(weight)], axis=1).astype(np.float32)+ act = np.tile(np.array([[0.25, 0.75]], dtype=np.float32), (len(ids), 1))+ return [logits, act]+++def _bare_onnx(lang_temperatures=None):+ a = ONNXAgent.__new__(ONNXAgent) # skip __init__: no onnxruntime, no checkpoint+ a.model_id = "stub"+ a.cfg = {"max_len": 64, "head_max_len": 32}+ a.tok = _FakeTok()+ a.temperature = [1.0, 1.0, 1.0]+ a.temperature_by_options = {}+ a.session = _StubSession()+ a.hooks = ()+ a.hooks_raise = True+ a.hooks_concurrent = True+ a.hooks_timeout = None+ a._hooks_lock = None+ a._hooks_mutex = threading.Lock()+ a.lang_temperatures = {}+ for l, cfg in (lang_temperatures or {}).items():+ norm = l.split("-")[0].lower()+ a.lang_temperatures[norm] = {+ "temperature": [clamp_temperature(t) for t in cfg["temperature"]],+ "temperature_by_options": {k: clamp_temperature(v)+ for k, v in cfg.get("temperature_by_options", {}).items()},+ }+ return a+++QUESTIONS = {+ "dept": {"type": "choice", "instructions": "Which team?",+ "criteria": {"billing": "money", "support": "help", "sales": "buy"}},+ "flag": {"type": "noul", "instructions": "Urgent?"},+}+STATES = ["aa", "bb", "c", "e"] # state token sums 54/56/29/31 -> four distinct mod-4 weights++# ---------------------------------------------------------------- contract+check_true("contract/predict_batch is defined", callable(getattr(ONNXAgent, "predict_batch", None)))+check_true("contract/system_one delegates to predict_batch",+ "self.predict_batch(" in inspect.getsource(ONNXAgent.system_one))+check_true("contract/predict alias preserved", ONNXAgent.predict is ONNXAgent.system_one)++_onnx_so = inspect.signature(ONNXAgent.predict_batch).parameters+_agent_so = inspect.signature(Agent.predict_batch).parameters+_shared = ["batch_size", "lang", "hooks", "on_predict_start", "on_predict_end", "hooks_raise",+ "max_len", "head_max_len", "min_confidence"]+check("contract/parameter names match Agent.predict_batch",+ [p for p in _shared if p not in _onnx_so], [])+check("contract/only Agent-only knobs are missing",+ sorted(set(_agent_so) - set(_onnx_so)), ["sort_by_length"])+++# ---------------------------------------------------------------- batched == sequential+sequential_agent = _bare_onnx()+sequential = [sequential_agent.system_one(s, QUESTIONS) for s in STATES]++agent = _bare_onnx()+batched = agent.predict_batch(STATES, QUESTIONS)++check("batch/one result per state", len(batched), len(STATES))+check("batch/answers match system_one exactly", batched, sequential)+check("batch/four states cost one session run", agent.session.calls, [2 * len(STATES)])+check_true("batch/result shape matches system_one",+ all(set(r) == {"model", "answers", "usage"} for r in batched))+check("batch/usage matches system_one", [r["usage"] for r in batched],+ [r["usage"] for r in sequential])+check_true("batch/states are distinguishable (so the parity check is not vacuous)",+ len({r["answers"]["dept"]["probabilities"]["billing"] for r in batched}) == len(STATES))++chunked = _bare_onnx()+chunked_results = chunked.predict_batch(STATES, QUESTIONS, batch_size=2)+check("batch/batch_size=2 chunks into two runs of two states each",+ chunked.session.calls, [2 * 2, 2 * 2])+check("batch/chunked results keep input order", chunked_results, sequential)+for batch_size in (0, -1, None):+ whole = _bare_onnx()+ check("batch/batch_size=%r still matches system_one" % batch_size,+ whole.predict_batch(STATES, QUESTIONS, batch_size=batch_size), sequential)+ check("batch/batch_size=%r does not chunk" % batch_size, whole.session.calls, [2 * len(STATES)])++# ---------------------------------------------------------------- empty and invalid input+empty = _bare_onnx()+check("empty/no states -> empty list", empty.predict_batch([], QUESTIONS), [])+check("empty/no states -> no session run", empty.session.calls, [])+no_q = _bare_onnx()+check("empty/no questions -> one zero-usage result per state",+ no_q.predict_batch(STATES, {}),+ [{"model": "laya-rl-agent-onnx", "answers": {},+ "usage": {"input_tokens": 0, "output_tokens": 0}}] * len(STATES))+check("empty/no questions -> no session run", no_q.session.calls, [])+check_raises("empty/bare string rejected", TypeError,+ lambda: _bare_onnx().predict_batch("just a string", QUESTIONS))+check_raises("empty/bare dict rejected", TypeError,+ lambda: _bare_onnx().predict_batch({"body": "x"}, QUESTIONS))+check_raises("empty/invalid question rejected before any run", ValueError,+ lambda: _bare_onnx().predict_batch(STATES, {"bad": {"type": "nope", "instructions": "?"}}))+check("budget/max_len and head_max_len forward through the batch path",+ _bare_onnx().predict_batch(STATES, QUESTIONS, max_len=32, head_max_len=16),+ [_bare_onnx().system_one(s, QUESTIONS, max_len=32, head_max_len=16) for s in STATES])++# ---------------------------------------------------------------- hooks+seen, events = [], []+++def _end_hook(ctx):+ events.append(ctx)+ seen.append([sorted(r["answers"]) for r in ctx.results])+++hooked = _bare_onnx()+hooked_results = hooked.predict_batch(STATES[:2], QUESTIONS, on_predict_end=_end_hook)+check("hooks/end hook sees the batched results", seen[-1], [["dept", "flag"]] * 2)+check("hooks/end hook usage aggregates every state", events[-1].usage["input_tokens"],+ sum(r["usage"]["input_tokens"] for r in hooked_results))+check_true("hooks/end hook sees elapsed_ms", isinstance(events[-1].elapsed_ms, float))++rewritten = _bare_onnx()+check("hooks/start hook can rewrite the states",+ rewritten.predict_batch(STATES[:1], QUESTIONS,+ on_predict_start=lambda ctx: setattr(ctx, "states", ["fff"])),+ [_bare_onnx().system_one("fff", QUESTIONS)])++skipped = _bare_onnx()+sentinel = [{"model": "cached", "answers": {}, "usage": {"input_tokens": 0, "output_tokens": 0}}]+check("hooks/start hook can serve cached results",+ skipped.predict_batch(STATES, QUESTIONS, on_predict_start=lambda ctx: ctx.skip(sentinel)),+ sentinel)+check("hooks/skip runs no session", skipped.session.calls, [])+++class _ErrorHook:+ def __init__(self, sink):+ self.sink = sink++ def on_error(self, ctx):+ self.sink.append(ctx.error)+++class _Boom:+ def run(self, names, inputs):+ raise RuntimeError("session failed")+++errors = []+failing = _bare_onnx()+failing.session = _Boom()+check_raises("hooks/session failure propagates", RuntimeError,+ lambda: failing.predict_batch(STATES, QUESTIONS, hooks=[_ErrorHook(errors)]))+check("hooks/error hook receives the failure once", [str(e) for e in errors], ["session failed"])+++# ---------------------------------------------------------------- min_confidence+gated = _bare_onnx()+results = gated.predict_batch(STATES, QUESTIONS, min_confidence=0.9)+flagged = [r["answers"]["dept"].get("low_confidence", False) for r in results]+check("min_confidence/flags exactly the answers below the threshold", flagged,+ [r["answers"]["dept"]["answer_confidence"] < 0.9 for r in results])+check_true("min_confidence/covers both branches", any(flagged) and not all(flagged), flagged)+check("min_confidence/raw answers stay intact",+ [r["answers"]["dept"]["probabilities"] for r in results],+ [r["answers"]["dept"]["probabilities"] for r in sequential])++flag_seen = []+_bare_onnx().predict_batch(+ STATES, QUESTIONS, min_confidence=0.9,+ on_predict_end=lambda ctx: flag_seen.append(+ [r["answers"]["dept"].get("low_confidence", False) for r in ctx.results]))+check("min_confidence/end hook sees the flags", flag_seen[-1], flagged)++check("min_confidence/unset adds no flag",+ any("low_confidence" in a for r in _bare_onnx().predict_batch(STATES, QUESTIONS)+ for a in r["answers"].values()), False)+check("min_confidence/0.0 is a no-op",+ any("low_confidence" in a+ for r in _bare_onnx().predict_batch(STATES, QUESTIONS, min_confidence=0.0)+ for a in r["answers"].values()), False)+check_raises("min_confidence/rejects out-of-range", ValueError,+ lambda: _bare_onnx().predict_batch(STATES, QUESTIONS, min_confidence=1.5))+check_raises("min_confidence/rejects a bool", ValueError,+ lambda: _bare_onnx().predict_batch(STATES, QUESTIONS, min_confidence=True))++# ---------------------------------------------------------------- lang on the batch path+lang_agent = _bare_onnx({"de": {"temperature": [3.0, 3.0, 3.0]}})+base_lang = lang_agent.predict_batch(STATES, QUESTIONS)+de_lang = lang_agent.predict_batch(STATES, QUESTIONS, lang="de")+check("lang/batch equals system_one with the same lang",+ de_lang, [lang_agent.system_one(s, QUESTIONS, lang="de") for s in STATES])+check_true("lang/override changes the batch probabilities",+ [r["answers"]["dept"]["probabilities"] for r in de_lang]+ != [r["answers"]["dept"]["probabilities"] for r in base_lang])+check("lang/hyphen subtag resolves on the batch path",+ lang_agent.predict_batch(STATES, QUESTIONS, lang="de-DE")[0]["answers"]["dept"]["probabilities"],+ de_lang[0]["answers"]["dept"]["probabilities"])+++# ---------------------------------------------------------------- Router integration+# The motivating failure: Router.predict_batch calls agent.predict_batch unconditionally, so an+# attached ONNX agent raised AttributeError on the batched entry point while predict worked.+router_agent = _bare_onnx()+router = Router(max_loaded=1, default="english")+router.attach("english", router_agent)+requests = [{"state": s, "questions": QUESTIONS, "model": "english"} for s in STATES[:2]]+routed = router.predict_batch(requests)++check("router/one routed result per request", len(routed), 2)+check("router/results carry the routing key", [sorted(r) for r in routed],+ [["answers", "model", "routing", "usage"]] * 2)+check("router/two states share one session run", router_agent.session.calls, [2 * 2])+++# --------------------------------------------------------------------------- report+print("\n%d passed, %d failed" % (len(PASS), len(FAIL)))+for f in FAIL:+ print(" FAIL " + f)+sys.exit(1 if FAIL else 0)++