Skip to content

perf+fix(onnx): tune ORT session, tokenize state once, report answer_confidence - #343

Merged
NandhaKishorM merged 1 commit into
NandhaKishorM:mainfrom
AlKor13:fix/onnx-perf-parity
Sep 24, 2026
Merged

NandhaKishorM merged 1 commit into
NandhaKishorM:mainfrom
AlKor13:fix/onnx-perf-parity

Conversation

@AlKor13

@AlKor13 AlKor13 commented Sep 24, 2026

Copy link
Copy Markdown
Contributor

Three independent gaps in ONNXAgent vs the PyTorch Agent, all validated against the multilingual checkpoint on CPU. Small diff (+26/-3), no API change.

1. answer_confidence — correctness parity (was a KeyError on backend swap)

The PyTorch Agent attaches answer_confidence (the calibrated max(p) confidence, on every question type — the value the README says to gate on) to each answer. ONNXAgent never did, so code that reads result["answers"][qid]["answer_confidence"] raised KeyError the moment it moved from torch to ONNX. Now emitted on choice/score/noul via the same common.answer_confidence.

2. Tokenize the shared state once — perf

_infer called build_sequence per question without state_ids, re-serializing and re-tokenizing the whole state on every question — the exact duplication the torch Agent already removed (_encode_state passes state_ids=). Now tokenized once and reused.

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 time.

Validation (multilingual checkpoint, CPU)

Parity with the torch Agent on the same input — identical decisions, and answer_confidence matching to 4 decimals:

question ONNX torch answer_confidence (ONNX / torch)
dept (choice) billing billing 1.0 / 1.0
urg (score) 1.04 1.04 0.6431 / 0.6432
refund (noul) 0.996 0.996 0.9963 / 0.9963

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_confidence and serialize_state are already exported from laya.common; this only wires them into the ONNX decode/encode paths.
  • Validated manually (an ONNX e2e test needs an exported .onnx artifact, which isn't in CI); ruff + py_compile clean. Happy to add a gated test alongside tests/test_local_e2e.py if you want one.
  • Out of scope here (flagging for a follow-up): ONNXAgent also doesn't accept lang/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

… 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>
@NandhaKishorM

Copy link
Copy Markdown
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
NandhaKishorM merged commit 823be5c into NandhaKishorM:main Sep 24, 2026
21 checks passed
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants