Repository navigation
perf+fix(onnx): tune ORT session, tokenize state once, report answer_confidence - #343
Merged
Merged
Conversation
… answer_confidence Three independent gaps in ONNXAgent versus the PyTorch Agent, all validated against the multilingual checkpoint on CPU. 1. answer_confidence (correctness parity). The PyTorch Agent attaches `answer_confidence` (the calibrated max(p) confidence, on every question type) to each answer; ONNXAgent did not. Code that reads `result["answers"][qid]["answer_confidence"]` — the value the docs say to gate on — raised KeyError when swapped from torch to ONNX. Now emitted on choice/score/ noul via the same `common.answer_confidence`, so it matches torch to 4 decimals. 2. Tokenize the shared state once (perf). `_infer` called build_sequence per question without `state_ids`, re-serializing and re-tokenizing the whole state each time — the exact duplication the torch Agent already removed. Tokenize once, pass `state_ids=`. 3. ORT session graph optimization (perf). Sessions were built with no SessionOptions, so ORT ran the unoptimized graph. Enable ORT_ENABLE_ALL (operator fusion / constant folding) on both the primary and CPU-fallback session; functionally neutral, free at inference. Validated (multilingual, CPU): decisions and answer_confidence identical to torch (e.g. billing/1.04/0.996; answer_confidence 1.0/0.6431/0.9963 vs torch 1.0/0.6432/0.9963), ONNX 11 ms vs torch-eager 143 ms on the same inputs. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Owner
|
Thank you for this, it is a tidy and well-validated change. ONNX users now get answer_confidence just like the PyTorch Agent, the state is tokenized once instead of once per question, and ONNX Runtime now optimizes the graph. I reproduced exact probability parity with the torch Agent on a local checkpoint. A gated ONNX test and the lang_temperatures follow-up you mentioned would both be very welcome. Merging. |
NandhaKishorM
added a commit
that referenced
this pull request
Sep 24, 2026
#343 made ONNXAgent._infer tokenize the shared state once before build_sequence, and #376 started running test_audit_regressions under pytest in CI. The test's object() stand-in has no mask_token and is not callable, so every Python lane failed. The stub now provides both; build_sequence stays patched out. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Suzzt
added a commit
to Suzzt/laya
that referenced
this pull request
Sep 25, 2026
Review follow-up. `ONNXAgent` validates with `Agent._check_question`, so it accepted `option_order` and then encoded the canonical order anyway -- the same accepted-and- ignored failure this change set out to remove, just on the other backend. It now carries the key through `_to_internal`, passes it to `build_sequence`, and un-permutes the row before decoding, so both runtimes agree on what an order means. The inverse permutation is now one `unpermute_probs` helper in common.py rather than the same six lines in two decoders, which is also a smaller edit inside `_infer` -- worth something there, since NandhaKishorM#343 landed in the same region. README gains an "Option order" subsection under Decision Primitives, next to `labels`, the other optional question key: what the key is, that probabilities always come back in the caller's own option order, why it exists (the measured per-slot logits and NandhaKishorM#131), and the rotation-averaging loop with its measured effect. The example in it runs as written against the English checkpoint. tests/test_option_order.py grows to 52 checks: the helper over every permutation of four, the ONNX backend driven through `ONNXAgent.__new__` with a stub session so it needs neither onnxruntime nor a model file, and an assertion that the torch and ONNX decoders return the same answer for the same permuted row.
baninaveen
pushed a commit
to baninaveen/laya
that referenced
this pull request
Sep 25, 2026
NandhaKishorM#343 made ONNXAgent._infer tokenize the shared state once before build_sequence, and NandhaKishorM#376 started running test_audit_regressions under pytest in CI. The test's object() stand-in has no mask_token and is not callable, so every Python lane failed. The stub now provides both; build_sequence stays patched out. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Suzzt
added a commit
to Suzzt/laya
that referenced
this pull request
Sep 25, 2026
Review follow-up. `ONNXAgent` validates with `Agent._check_question`, so it accepted `option_order` and then encoded the canonical order anyway -- the same accepted-and- ignored failure this change set out to remove, just on the other backend. It now carries the key through `_to_internal`, passes it to `build_sequence`, and un-permutes the row before decoding, so both runtimes agree on what an order means. The inverse permutation is now one `unpermute_probs` helper in common.py rather than the same six lines in two decoders, which is also a smaller edit inside `_infer` -- worth something there, since NandhaKishorM#343 landed in the same region. README gains an "Option order" subsection under Decision Primitives, next to `labels`, the other optional question key: what the key is, that probabilities always come back in the caller's own option order, why it exists (the measured per-slot logits and NandhaKishorM#131), and the rotation-averaging loop with its measured effect. The example in it runs as written against the English checkpoint. tests/test_option_order.py grows to 52 checks: the helper over every permutation of four, the ONNX backend driven through `ONNXAgent.__new__` with a stub session so it needs neither onnxruntime nor a model file, and an assertion that the torch and ONNX decoders return the same answer for the same permuted row.
Suzzt
added a commit
to Suzzt/laya
that referenced
this pull request
Sep 28, 2026
Review follow-up. `ONNXAgent` validates with `Agent._check_question`, so it accepted `option_order` and then encoded the canonical order anyway -- the same accepted-and- ignored failure this change set out to remove, just on the other backend. It now carries the key through `_to_internal`, passes it to `build_sequence`, and un-permutes the row before decoding, so both runtimes agree on what an order means. The inverse permutation is now one `unpermute_probs` helper in common.py rather than the same six lines in two decoders, which is also a smaller edit inside `_infer` -- worth something there, since NandhaKishorM#343 landed in the same region. README gains an "Option order" subsection under Decision Primitives, next to `labels`, the other optional question key: what the key is, that probabilities always come back in the caller's own option order, why it exists (the measured per-slot logits and NandhaKishorM#131), and the rotation-averaging loop with its measured effect. The example in it runs as written against the English checkpoint. tests/test_option_order.py grows to 52 checks: the helper over every permutation of four, the ONNX backend driven through `ONNXAgent.__new__` with a stub session so it needs neither onnxruntime nor a model file, and an assertion that the torch and ONNX decoders return the same answer for the same permuted row.
NandhaKishorM
pushed a commit
that referenced
this pull request
Sep 29, 2026
#181 built the truncation counts inside system_one. Since then main tokenizes the state once per call (#343), system_one delegates to predict_batch, and #569 took build_sequence's return_stats flag for the option-collapse stats. The previous commit therefore reports the counts through a second flag, return_truncation_stats. Here _encode_state asks for both and keeps the new counts as item["state_stats"] next to item["options"], and predict_batch writes them into each state's usage. The empty-questions usage is unchanged. test_hooks_api.py checks the new parameter's default. The tests follow the new item shape: test_truncation's stub tokenizer accepts main's truncation/max_length option cap and its source check reads _encode_state and predict_batch, and the _encode_state stubs in test_hooks, test_batch and test_predict_long carry state_stats. DecisionResult.usage is annotated Dict[str, Any], since truncated_questions is a list. The previous commit alone fails test_truncation.py; this one completes it. On the English checkpoint, answers and input_tokens match main at 11 state lengths (55 to 6,175 chars). truncated flips between 2,656 and 2,809 chars, where P(refund) for a state ending in the refund request drops from 0.9504 to 0.0000.
1 task done
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Three independent gaps in
ONNXAgentvs the PyTorchAgent, all validated against the multilingual checkpoint on CPU. Small diff (+26/-3), no API change.1.
answer_confidence— correctness parity (was aKeyErroron backend swap)The PyTorch
Agentattachesanswer_confidence(the calibratedmax(p)confidence, on every question type — the value the README says to gate on) to each answer.ONNXAgentnever did, so code that readsresult["answers"][qid]["answer_confidence"]raisedKeyErrorthe moment it moved from torch to ONNX. Now emitted on choice/score/noul via the samecommon.answer_confidence.2. Tokenize the shared state once — perf
_infercalledbuild_sequenceper question withoutstate_ids, re-serializing and re-tokenizing the whole state on every question — the exact duplication the torchAgentalready removed (_encode_statepassesstate_ids=). Now tokenized once and reused.3. ORT session graph optimization — perf
Sessions were built with no
SessionOptions, so ORT ran the unoptimized graph. EnableORT_ENABLE_ALL(operator fusion / constant folding) on both the primary and CPU-fallback session. Functionally neutral, free at inference time.Validation (multilingual checkpoint, CPU)
Parity with the torch
Agenton the same input — identical decisions, andanswer_confidencematching to 4 decimals:Speed on the same inputs: ONNX 11 ms vs torch-eager 143 ms. (I also measured ~1.45x CPU / ~1.75x GPU on a larger 5-question batch; the win scales with how much of the call is the forward pass.)
Notes
answer_confidenceandserialize_stateare already exported fromlaya.common; this only wires them into the ONNX decode/encode paths..onnxartifact, which isn't in CI); ruff +py_compileclean. Happy to add a gated test alongsidetests/test_local_e2e.pyif you want one.ONNXAgentalso doesn't acceptlang/lang_temperatures, so per-language confidence calibration isn't applied on the ONNX path — I can send that separately since it touches the constructor signature.🤖 Generated with Claude Code