mirror of
https://github.com/Niko1221/Strata.git
synced 2026-12-03 19:03:30 +07:00
[PR #2639] [CLOSED] [Engine] Jev System One decision endpoint (/v1/systemone): typed decisions with calibrated probabilities #4183
Labels
No labels
needs-format
pull-request
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference
Niko1221/Strata#4183
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
📋 Pull Request Information
Original PR: https://github.com/Niko1221/Strata/pull/2639
Author: @justindressler
Created: 10/15/2026
Status: ❌ Closed
Base:
main← Head:jev-port📝 Commits (10+)
8a23baatest(systemone): RED - /v1/systemone validation, readout math, frozen prompt (10 failing)00924bcfeat(systemone): M3.0 GREEN - POST /v1/systemone decision endpoint26cac67test(brow): RED - StrataEngine.final_row_logits wire (BROW->BROWD, fail-closed)d288ceffeat(brow): GREEN - StrataEngine.final_row_logits (BROW->BROWD wire, fail-closed) + jev.handle wired to real contract609d6aetest(brow-engine): RED - Verifier::brow_row fail-closed pre-run contract (CUDA test target)b3b1370feat(brow-engine): GREEN - Verifier::brow_row (fail-closed row gather, CUDA+Metal), --jev-brow flag, serve-loop BROW handler; golden battery fixture2b12ee6test(jev-golden): battery harness - 12 items, invariants+repeat determinism; CMake CPU guard fixed (15/15)532f342fix(jev-brow): restore the usage() indent the --jev-brow insertion swallowed (review r1)3801bd7feat(jev-calib): M3.2 calibration port - Platt+temperature, donor apply order, /admin/calib hot-swap, B1.1 log rowsd912827fix(jev-render): donor prompt fidelity - three render bugs found by the live M3.2 bench📊 Changes
43 files changed (+6210 additions, -0 deletions)
View changed files
📝
CMakeLists.txt(+5 -0)➕
calib/README.md(+36 -0)➕
calib/bench_suite.py(+444 -0)➕
calib/blockers_gpu.py(+328 -0)➕
calib/calib-D.json(+8 -0)➕
calib/calib-L.json(+8 -0)➕
calib/calib-S.json(+8 -0)➕
calib/convert_benchmarks.py(+185 -0)➕
calib/token_audit.py(+75 -0)➕
docs/JEV-PR.md(+372 -0)➕
docs/JEV-SYSTEMONE.md(+112 -0)➕
docs/bench-artifacts/audit-image-sample.json(+267 -0)➕
docs/bench-artifacts/audit-real-sample.json(+126 -0)➕
docs/bench-artifacts/audit-text-sample.json(+562 -0)➕
docs/bench-artifacts/blockers/cis-brier.json(+41 -0)➕
docs/bench-artifacts/blockers/error-D.json(+4 -0)➕
docs/bench-artifacts/blockers/noise-floor.json(+53 -0)➕
docs/bench-artifacts/blockers/s-fit.json(+59 -0)➕
docs/bench-artifacts/blockers/soak-image.json(+12 -0)➕
docs/bench-artifacts/blockers/soak-text.json(+86 -0)...and 23 more files
📄 Description
Problem and result
Problem. Strata can dump logprobs for verification, but there is no per-request way to
read the logits of arbitrary label tokens at the final position. Without that, the engine
cannot serve a System One decision contract — a caller that wants a typed answer with a
calibrated probability (
noulyes/no,choicepick-one,scoreordinal) has to make themodel generate prose and then parse it, which is slow, unparsable in the failure case, and
gives a confidence the model chose to write rather than a number the caller can threshold.
Result. An opt-in engine wire (
--jev-brow) that returns the final-row logits forexactly the label tokens asked, plus a serve-layer
POST /v1/systemoneendpoint that appliesthe Jev readout math and per-tuple post-hoc calibration (Platt for
noul, temperature forchoice/score). One decode step produces a typed answer with a probability and a margin;the same model keeps serving chat, can answer decisions inside a chat call, and can decide
then narrate. Everything is gated by
STRATA_JEV_MODES; with it unset, the process behavesexactly like stock Strata (a decision surface that is not enabled returns
404, so probinglearns nothing).
Related discussion
reference implementation's wire and math onto the Strata engine. Opening it as a PR rather
than asking first is deliberate, and a maintainer can redirect it to an issue if that is
the preferred shape.
had considered — that is the same readout, used for a different purpose.
through
/reopen.Approach
Verifier::brow_rowinverify.hpp/.cppplusthe
--jev-browflag; final-row logits for a supplied token list, fail-closed on anymismatch. No change to existing decode paths.
/v1/systemonewith the donor's error contract (422+{"error": {"field": ...}}), the frozen D3 prompt block, and readout math ported fromjevcpp. Calibration is post-hoc and argmax-preserving, per tuple (
mode|qtype|set), hot-swappable through
POST /admin/calib, with donor-schema log rows for the offlinefit.py.STRATA_JEV_MODES=chat,decision(default for the jevport presets),decisionalone, or unset for stock behaviour; unknown tokens refuse to boot./v1/chat/completionsunless"jev"is present; nonew default; model format unchanged. Divergences from the donor plan are listed in §4d of
the detail below, each with the reason.
Validation
Revision: branch
jev-portheadfbffc99a, base296b59d2(v0.1.43 lineage).Environment: RTX 3090 24 GB, QFN = Qwen3.8-Flash-Next IQ3_XXS MoE, 32k ctx, calibration
tuple
p-jevcpp-qwen38-27b|q4_k_xl|timber|v1|V|all.Passed:
11 skipped.
NLL and ECE15 pre→post — table in §4a below.
quant): §4b below.
inline-chat shapes: §2 below.
Failed:
Not run:
main(v0.2.1.4,9de04cd4). This branch is 42 commits behindand
mergeable_stateisdirty, so a rebase is required before the numbers above can bere-claimed on the current tree. Queued next.
Limits
QFN/IQ3_XXS/32k. Another model or quant needs its own refit before the probabilities mean
anything — the PR ships the fitting path, not universal numbers.
lands (that is the separate suffix-reuse PR, #2351).
image_mode: directreads raw image embeddings; it was validated on the QFN vision pathonly.
Background and design detail
What a System One decision model is. Most uses of a language model are
"System Two": the model writes text and the caller reads, parses and trusts it. A
System One decision model does the opposite. It receives a state (text, JSON, or an
image) and a set of typed questions, and returns typed answers with calibrated
probabilities: a yes/no (
noul), a pick-one (choice), or an ordinal rating (score).It never generates prose to decide. Nothing has to be parsed, and the confidence is a number
the caller can threshold, route on, or log, rather than a sentence the model chose to write.
That makes it suited to fast, repeatable, auditable decisions inside a loop: routing,
guardrails, triage, scoring, and game or agent control.
Jev. "Jev" is TypeSafe's commercial System One decision API:
POST /v1/systemonewith{state, questions}, answers read from token probabilities rather than generated text. Itsrequest/response shape is the wire this work follows. Open implementations of the same idea
already exist (see References); the goals here are correctness, speed and honest
probabilities, not novelty.
Laya. Laya (
convaiinnovations/laya, Apache-2.0) approaches the same contract with adifferent mechanism: a small purpose-trained encoder (ModernBERT-large, 421M parameters;
non-autoregressive) that answers all questions in one forward pass (~33 ms reported),
trained with reinforcement learning against strictly proper scoring rules (RLCD) so that
honest probabilities are what maximises reward. Two things in its documentation shaped this PR: its probabilities ship
over-confident until a temperature is refit per question type and option count
(reported mean ECE 0.466 → 0.081, with the instruction to do this on your own data before
trusting them), and its comparison against Jev uses third-party published Jev figures
that it did not measure itself. We kept the first idea (per-tuple calibration, refit on
local data) and measured our own numbers on our own harness. The mechanism differs: a
general LLM read at its label logits, with no task-specific training.
jevcpp. The reference implementation this port follows: a llama.cpp-based server that
serves the Jev wire from a generative model by reading the label logits at the final
prompt position (Qwen3.8-27B, with a shipped calibration file and a metamorphic/golden test
set). Its plan and amendments define the request contract, the frozen prompt template, the
readout math and the test strategy that this PR ports.
What this PR does. It brings that System One surface to Strata. Strata's engine could
already dump logprobs for verification, but had no per-request way to read the logits of
arbitrary label tokens. This PR adds an opt-in
--jev-browengine wire (BROW) that returnsthe final-row logits for exactly the label tokens asked, and a serve-layer
/v1/systemoneendpoint that applies the Jev readout math and per-tuple post-hoccalibration (Platt scaling for yes/no, temperature scaling for choice/score) on top. The
same model keeps chat, and can answer decisions inside a chat call, from an image directly,
or decide-then-narrate. It is opt-in per process (
STRATA_JEV_MODES).Donor reference: jevcpp on Qwen3.8-27B (q4_k_xl), shipped calibration tuple
p-jevcpp-qwen38-27b|q4_k_xl|timber|v1|V|all(T_choice 1.5861). This port runs onQFN = Qwen3.8-Flash-Next IQ3_XXS MoE (RTX 3090, Strata engine v0.1.43-lineage, 32k ctx).
1. Features (the full jevcpp surface)
POST /v1/systemone{state, questions}— noul (yes/no), choice (letters), score (0-10 levels)enable_thinking=false, verbatim string states)--jev-browengine flag; final-row logits, fail-closedcalib-<mode>.json;POST /admin/calibhot-swap; donor-schema log rows forfit.pyX-Jev-Mode: V— per-option yes/no branches,p = softmax(s_yes − s_no), name-keyedimage_b64+image_mode:summary(vision → 160-tok summary → decide) ordirect(raw image embeddings + question, ONE readout)"then": {"generate": {...}}— answers folded into the last user turn, one wire requestPOST /v1/chat/completionswith `"jev": {stateError contract: donor's
422+{"error": {"field": ...}}. Streaming refused with thejev extension,
stateXORmessages,image_modevalidated, D+V refused with 422.2. Usage
Full surface + examples:
docs/JEV-SYSTEMONE.md. Refit calibration:calib/README.md(the suite IS the procedure). Mode gating:STRATA_JEV_MODESenv ("decision"= decision-only — no generation pathexists on the instance at all; outputs are probabilities over the caller's own
labels. Unset =
"chat"only: decisions are opt-in, and the jevport presets set"chat,decision"explicitly. Fail-closed on unknown tokens and on gatedroutes).
Why logit readout instead of asking the model for confidence: models asked to state their
own confidence are mostly overconfident with high calibration error (Groot &
Valdenegro-Toro, TrustNLP 2024, see References). Reading label probabilities from the
logits and calibrating them post-hoc on held-out data (Platt / temperature scaling) is the
standard alternative, and it is what this PR does; its measured effect is in section 4a.
Laya reaches the same conclusion from the training side: its probabilities also need a
temperature refit on local data before they can be trusted.
3. Test strategy
Unit (mock engine) — 73/73 green (jev modules; full serve/ discovery 858 run, 0 fail, 11 skipped): readout math invariants, prompt rendering
(byte-pinned noul/choice blocks — the Yes/No-swap regression is now a golden test),
per-tuple calibration isolation, V-mode softmax, image two-call/direct shapes,
decide-then-generate, chat-surface validation arms, 7×3 concurrency + FIFO
serialization.
Live suites (
calib/bench_suite.py): dev-split fit → held-out test eval,standard top-label ECE15 + mean NLL, per-item JSONL logs. Guards: Platt slope
a≤0 refused (label/prompt inversion detector — it caught a real bug), temperature
at search boundaries flagged.
Adversarial audit protocol (Justin's rule, 2026-10-15): 1-in-10 of all test
items re-verified by hand — text golds re-read from source passages, image items
regenerated from committed seeds with sha256 match against the logged hash, sampled
error images independently re-counted with vision. Result across text+image+real
suites: 0 scoring hallucinations, 0 gold errors, 1 documented CV-Bench ambiguity.
Artifacts:
audit-*.json,audit-imgs/,*-item-log.jsonl(920 rows).Real-benchmark converters (
calib/convert_benchmarks.py): POPE adversarial,CV-Bench, CountBenchQA via HF datasets-server; banned-field self-test (answer-bearing
fields never enter requests), sha256 image manifest, dev/test image-disjoint, POPE
sampled by image at exactly 50/50.
Vision strategy (externally reviewed before implementation):
6-arm design (D/S/S-QC/S-V/blind/shuffled — the last two are contamination
detectors), circular rotation for choice position bias, phased screen→full→frozen
PR gate.
4. Benchmarking results (all live, QFN IQ3_XXS, RTX 3090)
4a. Pre/post calibration (held-out test, offline replay of identical items)
*CVB n=20, bin-noise territory; NLL improves, acc flat. Fitted: L a=.6127 c=.6539
Tc=1.0557 Ts=2.263 · D a=1.0571 c=−.172 Tc=1.5456 Ts=.6555.
Also shown in
calib-prepost-ab.json: the OLD single global calibrator made imagetuples WORSE than raw (CountBench ECE .091→.451!) — the per-tuple fix is the story.
4b. Benchmark vs jevcpp's own benchmark (donor m2_baseline, same 3 tasks)
Donor: Qwen3.8-27B q4_k_xl, dense, its own server. Port: QFN IQ3_XXS MoE, Strata.
Same task sets (BoolQ / ARC / SST-5 slices from jevcpp's eval data), same metrics
code, post-calibration numbers:
*Both ECE variants are top-label, 15 bins; the donor scores each bin at its CENTER
((b+0.5)/15), this PR's harness scores the bin MEAN confidence. The donor-definition
column recomputes our logged raw_p under the donor's exact b13_eval formula so the
comparison is apples-to-apples. Under either definition the direction is the same.
The 26B-smaller IQ3 MoE matches the donor within ~1 standard error on noul and choice
(at n=100, SE≈3-5pp); score is −4.9pp (≈1 SE; the confounds are model size, MoE vs
dense, and quant — not separable at this n). Donor noul calibration HURT it
(0.905→0.890 acc); ours helps (0.890→0.910). SST-5 calibrated ECE remains ~5× the
donor's under both definitions — T_score=2.263 is doing damage control on a weak
5-way readout, not achieving donor-grade confidence. Stated plainly.
4c. Performance (warm, single client, n=10 per cell)
These cells are the warm-repeat regime (identical or near-identical prompts;
the engine's prefix mount fires). Instrumented per-turn measurements
(temporary build, since reverted) showed the two regimes explicitly, at a
67-token prompt: fresh question ≈ 1.0 s end-to-end (~0.97–1.14 s prefill +
decode + readout); identical repeat ≈ 0.35–0.45 s (mount skips prefill).
Multi-question requests and benchmark items are mostly fresh-prompt, so
expect the fresh column when prompts vary; the p50s above reflect settled
repeat traffic. Prefill dominates in both — that is the case for the
state-KV-reuse follow-up.
vs donor (27B dense, its m1_perf matrix, 1q-1c-warm): 71 ms p50 / 14.0 rps.
Measured budget of the port's ~350 ms (proxy, fresh connection), decomposed live:
Streaming is not a factor: systemone responses are single JSON bodies with
Content-Length (donor contract refuses
stream: true). The gap vs the donor isthe un-prefixed engine turn, not protocol overhead — the donor amortized prefill
across forks (prefix-once + seq_cp); this port re-prefills per request. State-KV
reuse / prefix-LRU (the separate suffix-reuse work, out of scope here) collapses
the prefill share and projects decisions to ~60–80 ms. Repeat-identical requests
already hit the engine's prefix mount: 278–300 ms via proxy, and long states
(~470 tok) repeat at the same cost, confirming the mount fires when the prompt is
a full prefix. Image direct ≈ text latency (encoder cached); summary costs ~6×
direct (full 160-token generation).
Determinism / noise floor (measured, mechanism identified): repeat-decision
probability drift on this engine is p99 |Δp| ≈ 0.04–0.07 with zero argmax
flips in 720 repeated decisions across idle, 8-decision and mixed 4-chat+4-
decision load (
blockers-run/noise-floor.json). The donor's 5e-3 gate was aDENSE-model gate and never applied here. Mechanism (verified in engine
source): MoE expert placement uses
atomicAddslot assignment(
src/prefill/moe_fused.cuplace_kernel), so row order inside each expert iswarp-dispatch order — nondeterministic per run; float addition is non-
associative, so the expert GEMM sums differ in the last ulp and the divergence
compounds across layers; IQ3_XXS keeps the wobble above dequant noise and the
readout softmax amplifies it near p≈0.5–0.9 (Δp ≈ p(1−p)·Δd). It is a property
of the model+engine pair, not of load — the three load scenarios measured the
same floor. Decision margins (>0.9 typical) exceed the floor by an order of
magnitude; fitted calibrators average it out over the dev split. A
deterministic-placement option (sort rows by source index after the atomic
fill) would lower it, as an upstream engine follow-up — out of scope here.
Single-item probability deltas smaller than this floor (e.g. POPE +1.6pp at
n=60) must not be read as signal.
4d. Not ported / diverged (deliberate, vs the donor plan)
--modes chat,decisiongatingSTRATA_JEV_MODESenv (A0.1) with a deliberate divergence: unset = chat only (donor defaulted both-on). Opt-in keeps an unconfigured Strata process behaviorally identical to stock, per the repo rule that a new feature is opt-in and the default path stays unchanged. Values:"chat"/"decision"/"chat,decision"; fail-closed 404 on gated routes, refuse-to-start on unknown tokens./admin/modesruntime flip not ported — restart is the policy boundary hereimage_mode: direct— same single-readout goal, no fork, D-tuple-calibrated, benched on POPE/CVB/CountBenchAll 10 pre-PR blockers from the Opus review
(pre-PR external review) are closed: strict per-tuple
fallback, per-tuple log files, B1.4 tuple refusal, fail-closed /admin/calib,
token audit (PASS), a211 metamorphic battery, noise floor (see 4c), soak
(2,200 req, 0 jev errors, VRAM drift 0.026%), S-tuple fit (live), bootstrap
CIs + Brier (
blockers-run/cis-brier.json).5. Artifacts
calib-prepost-ab.json— 4a's numbers + method (offline replay, identical items)perf-matrix.json— 4c (live measured)text-suite.md,image-suite.md,real-suite.md+*-item-log.jsonl— suite reportsconvert-manifest.json— real-benchmark provenance (sha256 per image)audit-text-sample.json,audit-image-sample.json,audit-real-sample.json— 1-in-10 auditsjevcpp/reports/m2_baseline.json,jevcpp/reports/m1_perf.json,jevcpp/calib/calib.json(all in the donor tree, not this repo)6. Scope of change, compatibility, and testing status
Engine diff (5 files, +149 lines, additive):
Verifier::brow_row(verify.hpp/.cpp),the
--jev-browflag andBROWserve-loop handler (generate.cpp), a CMake test target(
verify_brow_test, CUDA builds only), and its test. Everything is opt-in: the handlerruns only when
--jev-browis passed and the server sendsBROW; no existing requestpath changes. One line runs on every verify window regardless of the flag
(
last_row_T_ = T;inVerifier::run), an int store with no behavior change.Default behavior:
STRATA_JEV_MODESunset = chat only. Verified end to end with theenv var absent:
/v1/systemoneand the chatjevextension return 404, plain chatreturns 200. A stock Strata process is behaviorally unchanged.
Tested: CUDA build and GPU runs on an RTX 3090 (QFN IQ3_XXS, Qwen3.8-Flash-Next); the
full
serve/test discovery (858 tests) passes with the jev modules opted in.Not tested in this PR: HIP, SYCL and Metal builds.
brow_rowis written for thosebackends (the HIP compat headers map
cudaMemcpy*tohipMemcpy*; a Metal branch isincluded), but none of them was built or run as part of this PR.
7. References and prior work
Decision-model products and implementations
/v1/systemonewire thisfollows.
convaiinnovations/laya(Apache-2.0).https://github.com/NandhaKishorM/laya, model card
convaiinnovations/laya. Source of theRLCD training description, the one-forward-pass encoder design, and the per-(question
type, option count) temperature-refit finding. Its README cites third-party Jev
measurements of 236–276 ms p50 (AbdelStark/jev-benchmarks, nibzard/decision-model-benchmark).
PLAN.md,PLAN.amendments.md,DECISIONS.md,m2_baseline.json,m1_perf.json,calib.json(donor tree, not part of this repo). Its plan also lists open Jev-compatible projects as
prior art: DIY-Jev (Rust),
llm2jev,verdict,jevper,jev-compatible-server.Calibration
Regularized Likelihood Methods, 1999: the Platt scaling used for yes/no.
ICML 2017: temperature scaling (choice/score) and the Expected Calibration Error metric.
in Large Language and Vision-Language Models, TrustNLP 2024 (arXiv:2405.02917): LLMs and
VLMs asked to state their own confidence show high calibration error and are mostly
overconfident, the reason decisions are read from logits and calibrated externally.
Readout design (surveyed in
docs/research notes, 2026-10-15)lm-evaluation-harnessand HELM: loglikelihood multiple-choice scoring,single-token letter labels,
acc/acc_norm, and the smoke-test invariants adopted inthe golden battery.
top_logprobsclassification and top-1 − top-2 margin as the routing signal(returned on every answer here).
approach this design avoids, and its documented whitespace/prefix pitfalls.
The Latent Bridge (arXiv:2606.24470): why a single-pass fast path matters for
frame-rate decision loops.
Benchmarks used for calibration and evaluation: BoolQ, ARC, SST-5 (text); POPE
(adversarial), CV-Bench, CountBenchQA (image).
🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.