Disclaimer on AI-assisted preparation
Out of respect for the reader and in the interest of full methodological transparency, I disclose that this manuscript was produced with substantial AI assistance within a verified, agentic engineering workflow. AI systems were used for research support, critical review, code generation and review, mathematical typesetting, and prose drafting and editing. Responsibility for the manuscript, its claims, and its conclusions remains with the author. No substantive claim, measurement, or reported data point was accepted solely as the output of an autoregressive generative text-completion process. The workflow was deliberately evidence-first. The initial hypotheses were formulated by the author. AI-assisted research-using Consensus and systems from OpenAI/GPT, Anthropic/Claude, Google/Gemini, Qwen and Moonshot/Kimi-was then used to identify relevant concepts, principles, prior art, and research that the author had not previously considered. Benchmark cases were generated synthetically and manually reviewed. The reported benchmark results themselves were obtained by executing those cases against real, functioning inference systems and models, with repeated runs used to assess reproducibility and stability. The resulting evidence was critically reviewed by the author for plausibility, internal consistency, compatibility with prior art and published research, and agreement with the observed behavior of the implemented systems. The methodology and claims were developed from this evidence, not from model-generated prose. AI systems were additionally used as critics to search for inconsistencies, unsupported claims, methodological weaknesses, and plausible alternative interpretations. Agreement among these systems was treated as a review signal instead of proof. Code supporting the work was verified through unit, integration, and end-to-end testing where applicable. Only after the empirical and engineering evidence had been assembled and critically reviewed was AI used to help draft and edit the manuscript's prose under direct, aware, and detailed instructions from the author. AI assistance was also used to render mathematical formulas efficiently in MathML. The resulting manuscript, together with its supporting evidence and provenance records, was subsequently subjected to further multi-model review and criticism in agentic evaluation harnesses. Where such controls were available, inference systems were configured for low-temperature sampling and the highest available reasoning setting. The author then reviewed the manuscript again and conducted a separate AI-assisted editing pass focused exclusively on writing quality. Finally, the author proofread the complete manuscript and verified its contents, evidence, and presentation to the best of his knowledge and understanding. The use of AI described above should therefore not be understood as a substitute for empirical validation, source criticism, reproducibility, or authorial responsibility but as a part of a careful research, engineering, verification, and editorial workflow under efficiency goals.
Any causal language model already computes a categorical score over its vocabulary at every next-token boundary; a Jev-like typed-decision engine turns runtime-defined semantic answers into token verbalizers, stops inference after prefill, reads only those native logits, converts them with stable restricted softmax and chain-rule branch scoring, and deterministically reduces the resulting distribution into choice, score, or noul - without sampling and without generating an answer token. This paper breaks this method down. It explains how any causal language model can be turned into a typed-decision engine. Demonstrated as a paper with code, it addresses primarily applied AI engineers, AI research scientists, and curious tech-affine readers.
The reader should be able to follow the code, so the repository lineage matters as the typed-decision behavior implementation at hand is a server/runtime modification to a fork of llama.cpp.
Provenance as of 2026-09-22:
kyr0/Bonsai-Llama-Jev was forked from PrismML-Eng/llama.cpp.The core files introduced / changed for typed decisions are:
tools/server/SYSTEMONE.md
tools/server/server-context.cpp
tools/server/server-context.h
tools/server/server-task.h
tools/server/server.cpp
tools/server/tests/unit/test_chat_completion.py
The decisive implementation is in server-context.cpp: a new SERVER_TASK_TYPE_SYSTEMONE runs the normal model prompt forward pass, extracts selected logits at SLOT_STATE_DONE_PROMPT, sends those logits back to the HTTP-side decision logic, releases the inference slot, and returns before normal token generation starts.
This method crosses language-model, probability, and inference-runtime terminology. The terms below are used precisely throughout this document.
| Term | Meaning here |
|---|---|
| LM | Language model. |
| LLM | Large language model. Size is irrelevant to the method; the same readout principle applies to smaller causal LMs. |
| Causal / autoregressive LM | A model trained/inferred so token position predicts a distribution for the next token from earlier tokens. |
| Token | Integer symbol consumed/emitted by the model. A token is not necessarily one character or one word. |
| Tokenizer | Deterministic mapping between text and token IDs. Its context-sensitive segmentation is why answer-label validation is required. |
| Vocabulary | Finite set of token IDs the LM can predict. |
| Hidden state | Final internal vector at prompt position , before the LM output head. |
| LM head | Existing output projection that maps a hidden state to one score per vocabulary token. |
| Logit | Pre-softmax model score. In neural-network usage this usually means an unnormalized score; it should not be confused with the strict binary-statistics definition of log-odds. |
| Softmax | Function converting real-valued scores into positive normalized weights summing to 1. |
| Restricted softmax | Softmax computed only over the answer-token subset rather than over the whole vocabulary. |
| Verbalizer |
Mapping from a semantic class such as technical to one or more model tokens such as B.
|
| Prefill | Evaluation of the known input prompt. It produces model state/KV cache and logits at the prompt boundary before any generated continuation token. |
| Decode | Repeated continuation phase in which new output tokens are selected/appended and the model advances from them. |
| Sampler | Generation component that transforms/selects from logits using operations such as temperature, top-, top-, penalties, random sampling, or greedy selection. |
| KV cache | Cached attention Key/Value tensors for already-evaluated prefix tokens, allowing suffix continuations to avoid recomputing the full prefix. |
| Argmax | Index of the largest value. Used here to select the highest-probability semantic candidate after probability computation. |
| System One | TypeSafe API surface for asking typed questions over supplied state. "System One compatible" here refers to the request/response contract, not a claim about proprietary Jev internals. |
| Choice | Unordered finite-class primitive: return one selected semantic option and a distribution across options. |
| Score | Ordered finite-level primitive: return the probability-weighted expected level plus the distribution. |
| Noul | TypeSafe yes/no primitive: return the probability of "yes". |
| Calibration | Empirical property that predicted probabilities correspond to observed frequencies/correctness rates on a defined population. |
| NLL | Negative log-likelihood, a proper probabilistic scoring rule used when evaluating predicted class probabilities. |
| Brier score | Squared-error proper scoring rule for probabilistic predictions. |
| ECE | Expected Calibration Error: a binned summary of the gap between predicted probability and observed frequency; its value depends on the binning scheme. |
| GGUF | Model/container format used by llama.cpp-family runtimes. It is not part of the decision mathematics. |
Two distinctions are especially important:
An ordinary causal LM is already a next-token classifier over its vocabulary.
Given a tokenized prefix
the model computes a final hidden representation . Its language-model output head maps that hidden vector into one real-valued score for every vocabulary token:
Where:
The implementation (tools/server/server-context.cpp, logit readout at slot release):
const float * logits = llama_get_logits_ith(ctx_tgt, slot.i_batch - off);
for (llama_token token : slot.task->systemone_tokens) {
result->logits.push_back(logits[token]);
}
slot.release();
The ordinary next-token distribution of the model with parameters is:
Transformer decoders conventionally end in an output projection and softmax over possible symbols.
The typed-decision engine exploits a consequence that is easy to miss:
The LM already computed scores for every possible next token. If we encode each semantic answer as a known answer token, classification is already present in the final logits. We do not need the model to generate text explaining its choice.
This mirrors the verbalizer idea in prompt-based classification: semantic classes are mapped to token-level labels that the LM can score. PET (Pattern-Exploiting Training, Schick & Schütze, EACL 2021) is a well-known example of this general class-to-token interface.
Let:
choice, score, or noul).Composing these:
In practice (tools/server/server-context.cpp, request handler):
prompt = compile(state, question, candidates) # Phi: deterministic prompt + label map
logits = prefill(prompt) # f_theta: forward pass, stops before decode
q = softmax(logits[label_tokens]) # R: restricted readout
answer = reduce(q) # A: choice | score | noul
The model parameters are unchanged.
Put together:
No classifier head must be trained. No adapter must be attached. No sampler is necessary.
Saying "we implemented a different neural forward pass" is therefore slightly imprecise. The neural forward graph remains the same. What changes is the server execution path:
A normal generation engine conceptually performs:
prompt
v
prefill
v
logits z0
v
temperature / top-k / top-p / penalties / ...
v
sample or argmax y1
v
append y1
v
decode forward
v
logits z1
v
select y2
v
...
Generated text follows the autoregressive factorization:
A generation engine therefore contains a serial decode loop.
For a one-token label set:
state + question + candidates
v
deterministic prompt
v
prefill
v
final-position logits z
v
gather z[A], z[B], z[C], ...
v
restricted softmax
v
typed reduction
v
JSON response
There is no generated token between the model and the typed answer.
In the current implementation:
SERVER_TASK_TYPE_SYSTEMONE
v
normal prompt evaluation
v
SLOT_STATE_DONE_PROMPT
v
llama_get_logits_ith(...)
v
copy logits for task.systemone_tokens
v
queue result
v
slot.release()
v
return
The normal sampler chain is never entered.
Consequences:
top-k;top-p;"A" and then an explanation;usage.output_tokens == 0 for this local method.The only argmax is later applied to the semantic candidate probability vector. That is classification, not greedy text decoding.
Removing sampling removes an explicit stochastic operation. It does not guarantee bit-identical outputs across:
Cross-backend equivalence still requires numerical tolerances.
Suppose the application asks:
{
"state": "The Stripe integration has failed for three days and sales are being lost.",
"questions": {
"department": {
"type": "choice",
"instructions": "Which team should handle this?",
"criteria": {
"billing": "Payments and subscriptions",
"technical": "Bugs and integrations",
"sales": "Pricing and account questions"
}
}
}
}
The engine does not ask the model to generate "technical".
Instead:
A -> billing
B -> technical
C -> sales
The semantic names/descriptions enter the prompt; the output boundary uses a tiny label alphabet.
semantic class verbalizer
------------------ ----------
billing A
technical B
sales C
The current repository uses:
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
giving 62 single-character labels.
The direct readout is exact only if an answer character really is one token at the exact prompt boundary.
Let:
Require:
That means:
A adds exactly one token;A;The repository explicitly verifies these properties.
The implementation enforces this directly:
const auto prefix = common_tokenize(ctx_server.vocab, prompt, true, true);
const auto extended = common_tokenize(ctx_server.vocab, prompt + label, true, true);
if (extended.size() != prefix.size() + 1 || !std::equal(prefix.begin(), prefix.end(), extended.begin()) ||
common_token_to_piece(ctx_server.vocab, extended.back()) != label ||
std::find(letters.begin(), letters.end(), extended.back()) != letters.end()) {
throw std::invalid_argument("Answer label " + label + " is not a distinct single token at the answer boundary ...");
}
In code: tools/server/server-context.cpp, answer-label validation.
This matters because BPE (byte-pair encoding) and unigram tokenizers can merge punctuation, whitespace, and following text. It is possible that:
tokenize("answer:")
is not a prefix of:
tokenize("answer:A")
The current engine therefore fails with HTTP 422 rather than silently scoring the wrong token.
Hence "any LM" should be qualified:
The current implementation supports a causal next-token LM whose tokenizer/chat-template combination provides usable singleton answer tokens at the output boundary.
A generalized prefix-trie implementation can remove that restriction.
Assume candidates use one-token verbalizers:
The LM returns full-vocabulary logits . We copy only:
Compute:
This is a restricted softmax over answer tokens. Softmax converts arbitrary real scores into positive normalized weights summing to one.
The implementation (tools/server/server-context.cpp, probabilities()):
const size_t best = std::max_element(logits.begin(), logits.end()) - logits.begin();
std::vector<double> probabilities;
double total = 0.0;
for (float logit : logits) {
const double weight = std::exp(double(logit) - logits[best]);
probabilities.push_back(weight);
total += weight;
}
for (double & probability : probabilities) {
probability /= total;
}
Full-vocabulary probability:
Condition on the next token being one of the allowed candidate labels :
Substitute full softmax:
where:
The vocabulary denominator cancels:
In words:
test_systemone_matches_native_probabilities:
A/B token IDs;A and B;/v1/systemone.Agreement is checked to approximately .
For single-token candidates, System One exposes the backbone's existing probability geometry under a restricted label space.
Naive exponentiation can overflow for large logits.
Shift every logit by the largest logit first:
and exponentiate the shifted scores instead:
The result is unchanged because the common factor cancels.
The standard max-subtraction/log-sum-exp stabilization technique.
In practice (tools/server/server-context.cpp, probabilities()):
m = max(z)
q[i] = exp(z[i] - m) / sum(exp(z[j] - m)) # same result, no overflow
The current implementation performs probability arithmetic in double, although copied logits arrive as float.
Suppose the copied answer-token logits for three candidates A, B, C are:
A / billing: 2.1
B / technical: 0.9
C / sales: -0.1
Subtract :
Exponentiate:
Normalize:
Dividing each weight by Z:
The choice is candidate A.
No answer token was generated.
In practice (tools/server/server-context.cpp, probabilities()):
logits = [2.1, 0.9, -0.1] # copied z values at the A/B/C token positions
p = softmax(logits) # [0.7082, 0.2133, 0.0785]
choice = candidates[argmax(p)] # "A" - no token generated
For , labels use multiple characters, because the set of single-character labels is exceeded (see 6.).
Let the label width be (characters per label), and let be the number of distinct symbols allowed at label position (its radix):
Capacity:
Require:
The implementation searches for radix sizes that minimize capacity and then prefix-readout cost.
For 67 candidates:
radices = 2 x 34
capacity = 68
For label BA, the second character must be scored conditional on B.
By the probability chain rule:
More generally:
The standard probability chain rule, applied to label characters.
The current engine uses a restricted categorical probability at every branch:
Where: = the label characters already chosen before branch ; = the allowed symbols at branch ; = the model's logit for symbol at the prompt extended by .
For candidate with label , multiply the branch probabilities along the label's character path ( is the character at position , the characters before it):
Finally, normalize these path weights over all candidates:
The implementation (tools/server/server-context.cpp, depth readout loop):
size_t stride = 1;
for (size_t depth = 0; depth < width; ++depth) {
const size_t count = question.alphabet_sizes[depth];
for (size_t offset = 0; offset < stride && offset < question.keys.size(); ++offset) {
server_task task(SERVER_TASK_TYPE_SYSTEMONE);
task.params.cache_prompt = depth > 0; // later prefixes reuse the slot KV
task.tokens = tokens.clone();
size_t index = offset;
for (size_t i = 0; i < depth; ++i) {
task.tokens.push_back(letters[index % question.alphabet_sizes[i]]);
index /= question.alphabet_sizes[i];
}
task.systemone_tokens.assign(letters.begin(), letters.begin() + count);
// ...
}
if (depth + 1 < width) {
stride *= count;
}
}
For multi-character labels this is best understood as a forced categorical decision tree.
It is not exactly the raw unrestricted language-model probability of the complete label string, because every branch is renormalized over valid answer symbols:
The engine asks:
Among valid answer symbols at this branch, how does the model distribute support?
That is the desired quantity for a typed classifier.
For radices , the total number of model readout evaluations is:
with empty product .
In practice (tools/server/server-context.cpp, readout loop over label depths):
R = sum(prod(radix[:d]) for d in range(D))
# e.g. radices 2x34: 1 + 2 = 3 logit readouts per request
Examples from the implementation:
| Candidates | Radices | Capacity | Readouts |
|---|---|---|---|
| 27 | 27 | 27 | 1 |
| 53 | 53 | 53 | 1 |
| 62 | 62 | 62 | 1 |
| 63 | 3 x 21 | 63 | 4 |
| 67 | 2 x 34 | 68 | 3 |
| 100 | 2 x 50 | 100 | 3 |
| 677 | 17 x 40 | 680 | 18 |
| 3844 | 62 x 62 | 3844 | 63 |
| 3845 | 2 x 37 x 52 | 3848 | 77 |
"No decoding" does not mean "one neural evaluation for arbitrary candidate counts."
For (single-character label case), one final-position readout is enough per question.
For wider labels, deterministic prefix branches require additional suffix evaluations. They are still not sampled/generated outputs.
The KV cache stores previously computed attention keys and values.
Without reuse:
prompt + A
prompt + B
prompt + C
would each repeat the entire prompt computation.
With reuse:
prefill(prompt) -> KV(prompt)
branch A -> suffix only
branch B -> suffix only
branch C -> suffix only
The current server sets:
task.params.cache_prompt = depth > 0;
for deeper label-prefix readouts.
Cache reuse changes performance, not probability semantics. Cache eviction or slot scheduling can still force reevaluation.
The alphanumeric scheme is practical, but a fully portable engine should support candidate verbalizers of arbitrary token length.
Construct a prefix trie:
root
/ \
token 91 token 42
/ \ \
17 88 5
At every node:
Suggested abstraction:
struct DecisionCandidate {
std::string semantic_id;
std::vector<llama_token> verbalizer;
};
struct DecisionTrieNode {
std::map<llama_token, NodeId> edges;
std::optional<size_t> candidate;
};
The runtime then needs only:
SelectedLogits score_next(
PrefixState prefix,
span<const llama_token> allowed_tokens);
After obtaining:
the API primitives are deterministic reductions.
Choice returns the index of the most probable candidate:
TypeSafe's public Choice contract similarly exposes the selected option, a probability per supplied option, and confidence.
The implementation (tools/server/server-context.cpp, answer()):
const size_t best = std::max_element(probabilities.begin(), probabilities.end()) - probabilities.begin();
// ...
output["choice"] = keys[best];
For ordered levels , the score is the expected level index (a probability-weighted average):
TypeSafe documents exactly this probability-weighted-level interpretation; for example, probabilities over levels yield score .
The implementation (tools/server/server-context.cpp, answer()):
double score = 0.0;
for (size_t i = 0; i < keys.size(); ++i) {
// ...
score += i * probabilities[i];
}
// ...
output["score"] = score;
TypeSafe defines Noul as a yes/no question returning the probability of "yes".
Internally:
yes
no
with:
The current implementation computes:
Since:
this simplifies to:
The implementation (tools/server/server-context.cpp, answer()):
return {{"type", type}, {"noul", (probabilities[0] + 1.0 - probabilities[1]) * 0.5}};
confidence field is a local heuristicLacking any better known option, we currently compute the returned confidence as the probability of the winning candidate multiplied by the probability that every other candidate loses:
A deterministic concentration heuristic.
The implementation (tools/server/server-context.cpp, answer()):
double confidence = probabilities[best];
for (size_t i = 0; i < keys.size(); ++i) {
// ...
if (i != best) {
confidence *= 1.0 - probabilities[i];
}
}
It is not a theorem that:
For binary winner probability :
Numerically:
For the previous three-class example:
so:
TypeSafe's public docs describe confidence as derived from how spread/peaked the probability distribution is; with no further information about Jev's implementation, we cannot establish this local formula as Jev's production formula.
Downstream systems should distinguish:
The direct readout is exact relative to the model and prompt:
That does not imply:
The readout inherits:
Softmax over allowed answer tokens is conditional on the supplied alternatives and is not automatically operationally calibrated confidence.
Zhao et al. show that language-model classification can be highly sensitive to prompt format, example ordering, and answer biases, motivating contextual calibration. This should be considered as well.
The safest interpretation is:
Given this prompt and these alternatives, how does this backbone distribute its answer preference among them?
If the candidate set is incomplete, the probabilities still sum to one.
Use other, none, insufficient evidence, or an abstention class when the task is genuinely open-set.
Suppose the engine produces scores . A post-hoc temperature parameter can transform them:
The implementation (tools/server/server-context.cpp, calibration apply()):
const double effective = temperature_for(question_type);
// ...
const double beta = 1.0 / effective;
for (double probability : probabilities) {
const double value = beta * std::log(std::max(1e-12, probability));
log_weights.push_back(value);
peak = std::max(peak, value);
}
for (double & value : log_weights) {
value = std::exp(value - peak); // p_i^(1/T), max-shifted
z += value;
}
// ... then value /= z to renormalize
Fit on a held-out calibration set by minimizing the negative log-likelihood (NLL) of the correct labels.
Guo et al. found temperature scaling to be a simple and often effective post-hoc calibration method for neural classifiers.
These may use mathematically similar divisions by , but serve different purposes.
Sampling temperature
logits -> temperature -> token-selection sampler
belongs to generation.
Calibration temperature
decision scores -> fitted T -> deterministic probabilities
is a deterministic probability mapping.
A calibrated decision engine can still correctly claim no sampling.
Do not fit calibration parameters on the final test set.
Keep the splits separate:
training/model data
v
calibration/validation split
v
untouched test split
Operationally the decision function is not only:
but:
where includes:
The current implementation builds a structured payload conceptually resembling:
{
"evidence": "...",
"criterion": "...",
"options": [
{
"letter": "A",
"name": "billing",
"description": "Payments and subscriptions"
}
]
}
and applies the model's normal chat template with thinking disabled.
Mapping a semantic candidate to A instead of B changes the rendered prompt.
Treat candidate permutations as a semantic-stability test.
Control tokens, whitespace and the chat template itself remain important.
They determine:
Tokenizer validation must therefore operate on the fully rendered prompt.
In Bonsai-Llama-Jev, the System One API is added alongside the existing OpenAI API and llama.cpp native HTTP APIs:
server.cpp registers:
POST /v1/systemone
with 422-style request validation.
Question types:
choice
score
noul
systemone_question in server-context.cpp:
Each used answer character must:
server-task.h introduces:
SERVER_TASK_TYPE_SYSTEMONE
plus:
llama_tokens systemone_tokens;
and need_logits() returns true for the task.
At prompt completion, the key path is effectively:
const float * logits =
llama_get_logits_ith(ctx_tgt, slot.i_batch - off);
for (llama_token token : slot.task->systemone_tokens) {
result->logits.push_back(logits[token]);
}
queue_results.send(...);
slot.release();
return;
That return is the decisive boundary.
The HTTP-side path:
output_tokens = 0.A portable engine can expose one primitive:
score_allowed_next_tokens(prefix, allowed_token_ids) -> logits[]
With it:
function decide(state, questions):
answers = {}
for question in questions:
candidates = compile_candidates(question)
prompt = render_prompt(state, question, candidates)
verbalizers = compile_and_validate_verbalizers(prompt, candidates)
trie = build_prefix_trie(verbalizers)
path_weight = array(candidate_count, 0.0)
queue = [(root, tokenize(prompt), 1.0)]
while queue not empty:
node, prefix_tokens, node_weight = queue.pop()
outgoing = node.outgoing_token_ids
logits =
prefill_or_cached_suffix_forward(
prefix_tokens,
outgoing
)
local_p = stable_softmax(logits)
for each edge(token -> child):
child_weight =
node_weight * local_p[token]
if child is terminal:
path_weight[child.candidate] += child_weight
else:
queue.push(
child,
prefix_tokens + [token],
child_weight
)
p = normalize(path_weight)
answers[question.id] =
typed_reduce(question.type, p)
return {
answers,
usage: {
input_tokens: logical_input_usage,
output_tokens: 0
}
}
Normal generation of output tokens costs approximately:
A one-token typed decision replaces those decode steps with a single logit readout () and the restricted softmax (), so it costs approximately:
gather + softmax + reducer is tiny relative to a large Transformer forward.
In practice (tools/server/server-context.cpp, readout at slot release):
# generation: prefill + K x decode_step (K serial rounds)
# decision: prefill + read_logits(answer_tokens) # slot freed before generation
The system also avoids:
For independent questions, tasks can also be batched by the server.
A request may contain many questions.
The current server can schedule/batch their work together, but each question has its own criterion/options and therefore its own compiled prompt.
In particular:
parallel/batched inference
does not imply:
one shared hidden state answers every question
For one-character labels:
For multi-character labels:
Read the final prompt position:
final prompt position
v
next-token logits
The current implementation.
The flow becomes:
encoder(state/question/options)
+
decoder start state
v
decoder token logits
The restricted-softmax logic still applies.
For a BERT-like model:
prompt containing [MASK]
v
hidden state at [MASK]
v
vocabulary logits
v
restricted verbalizer softmax
An embedding model has no token-prediction head, so this exact method does not apply. It requires a classifier, reranker, or similarity rule.
More precisely, "any LM" means:
any model exposing an appropriate token-prediction distribution through its inference runtime.
For multimodal causal models:
image/audio/text state
v
multimodal prefill
v
final LM logits
v
same selected-token readout
v
same typed math
The current repo's System One media extension uses the existing multimodal parser/projector.
A text-only model remains text-only.
The method makes eight claims that can be checked mechanically. Each invariant below is a contract: it names one property every correct implementation must have. Section 27 turns them into executable tests.
Every semantic candidate has exactly one verbalizer path.
Every verbalizer is exactly the token path evaluated at the real prompt boundary.
For every selected token , decision mode returns the model's native .
The returned candidate probabilities always form a proper probability distribution over the supplied candidates:
Decision mode emits no sampled model token.
Changing:
top_k
top_p
min_p
sampling temperature
penalties
must not alter decision probabilities.
Cache reuse may change latency but not semantic output beyond numerical tolerance.
Typed-decision support must not alter ordinary chat/completion behavior.
Every invariant of section 26 maps to a test, and every test follows the same pattern: the typed-decision path is compared against an oracle, and any disagreement beyond numerical tolerance is a defect. The oracle is the model's ordinary completion path, which computes full-vocabulary next-token probabilities through the regular API.
Verify:
The right-hand side is the oracle: the same label probabilities from the ordinary completion path, renormalized over the allowed answer set. Agreement within numerical tolerance shows that the readout adds no distortion of its own.
Test across:
Multi-character labels are verified against the same oracle, depth by depth: at every label prefix, the engine's restricted softmax must match the native distribution at that prefix, renormalized over the allowed next characters. For every prefix:
Tokenizers merge characters across boundaries, so probe the label alphabet where this is most likely:
" A" tokens;Fail rather than approximate.
Run the same decision request under many sampler settings: temperature, top-k, top-p, penalties. The sampler is never entered in decision mode, so the answers must not change at all.
Permute option order, map outputs back to semantic IDs, then measure:
Compare identical requests with prefix-cache reuse on and off.
Expected:
same probabilities
different compute cost
Repeat and overlap requests to shake out slot and cache cross-talk:
When calibration is enabled, measure it on untouched labeled data (no fitting, no tuning on these rows) and report:
Recurring misunderstandings about the method, and why each is wrong:
No.
Greedy decoding selects a token, appends it, and continues decoding.
Decision mode reads scores and returns structured data.
No.
Temperature 0 is usually a generation-path convention.
This method bypasses the generation sampler.
Not without calibration evidence.
It is a restricted model probability under a particular prompt/candidate set.
No.
Structural compatibility and semantic decision quality are separate.
Not necessarily.
They are separately compiled readouts that can be batched.
No.
The model weights/graph stay intact. The runtime exposes a different readout and termination point.
For new implementations, the method splits into four independent layers. Each layer can be replaced or reused on its own; only the interfaces between them are fixed:
+--------------------------------------------+
| 1. Typed API / validation |
| state, model, questions |
+------------------+-------------------------+
v
+--------------------------------------------+
| 2. Decision compiler |
| semantics -> prompt + verbalizers |
| tokenizer validation |
+------------------+-------------------------+
v
+--------------------------------------------+
| 3. Inference primitive |
| prefill / cached suffix |
| selected native logits |
| NO sampler / NO decode loop |
+------------------+-------------------------+
v
+--------------------------------------------+
| 4. Probability + reducer |
| stable softmax / chain rule |
| choice | score | noul |
| optional calibration |
+--------------------------------------------+
The backend does not need to know the meaning of choice, score, or noul.
It only needs:
struct LogitReadoutRequest {
TokenSequence prefix;
std::vector<TokenId> selected_tokens;
PrefixCachePolicy cache_policy;
};
struct LogitReadoutResult {
std::vector<float> logits;
size_t logical_input_tokens;
};
Semantics:
evaluate prefix
do not sample
do not generate
return z[token_id] for requested token IDs
In llama.cpp, the underlying capability already exists through:
llama_get_logits_ith(...)
The implementation task is exposing it at the correct server lifecycle boundary.
It transforms:
Properties:
The most accurate description is:
a discriminative readout layer over a generative language-model backbone
rather than "prompting an LLM to output JSON."
Energy consumption and time spent are reduced, and with them the cost.
The method is useful for every non-open question format. If a question can be formulated or re-formulated as a closed question, the method applies.
It establishes:
It does not by itself establish:
Cloudflare currently describes Jev as a structured evaluation model that answers typed Noul/Choice/Score questions with calibrated answers, probabilities, and confidence. That is a product-level contract/claim, not a public architectural specification.
The local engine should therefore be described as Jev-like / System-One-compatible, not as a reproduction of undisclosed Jev internals.
The current engine rejects a question with HTTP 422 when an answer label is not a distinct single token at the rendered prompt boundary (see 7.). That restriction is an implementation convenience, not a property of the method.
A generalized prefix-trie readout removes it. The compiler builds a trie over the tokenizations of all candidate labels; the engine then walks the trie and, at every node, reads a restricted softmax over the child tokens. This extends the chain-rule machinery of section 11 from fixed positional alphabets to arbitrary token sequences:
The 422 then becomes the exception for labels that are genuinely unscorable, the 62 single-character label limit (see 6.) disappears, and the radix construction of section 11 becomes the special case of a balanced trie. Open questions are the per-branch renormalization semantics for labels of unequal token depth (a potential depth bias to study) and the readout budget: the readout-count formula of section 12 generalizes from radices to trie nodes, and deep or wide tries need the same cost analysis.
The deployable calibration artifact currently fits one temperature per question type (choice, score, noul) with a top-level fallback: Qtype-stratified temperature scaling, specified in the calibration protocol paper. The Bonsai-2-27B reference experiment found clearly different per-type temperatures (see 18.), which suggests residual miscalibration inside the types as well.
A schema v3 artifact could stratify further: bins by candidate count, label width, capability or domain, or predicted-confidence band, each with its own fitted temperature. A hierarchical fallback (bin -> question type -> global temperature) keeps low-count bins safe: when a bin has too little calibration data, its estimate falls back to the coarser level instead of overfitting a handful of cases.
The guardrails from the calibration protocol carry over unchanged: fit on a disjoint calibration split, recompute every derived answer field after scaling, judge the bins on held-out NLL, Brier score, and ECE, and keep estimator capacity low. More bins buy granularity at the price of overfitting risk; the convexity of the objective in the inverse temperature holds per bin, so each fitted bin temperature remains a well-behaved optimization.
The LM head maps the hidden state at the final prompt position to one logit per vocabulary token. This projection already exists in every causal LM; the engine only reads the entries it needs (see 3.).
The ordinary softmax over the full vocabulary: the model's native next-token distribution. The typed-decision readout is this distribution conditioned on the allowed answer labels (see 8.).
Softmax restricted to the logits of the answer tokens. the central identity of the method, equal to the native next-token distribution conditioned on the supplied labels (see 8.).
Subtracting the largest logit before exponentiation prevents floating-point overflow without changing the result (see 9.).
For multi-character labels, the restricted branch probabilities along the label's character path are multiplied (chain rule, see 11.).
The path weights are normalized over all candidates so the resulting probabilities sum to one (see 11.).
The choice answer is the candidate with the highest probability (see 15.1).
The score answer is the probability-weighted average of the ordered level indices (see 15.2).
The noul answer is the probability of "yes"; for binary yes/no labels the averaged form reduces to this (see 15.3).
The current local confidence heuristic: the winner's probability multiplied by the probability that every other candidate loses. A deterministic heuristic, not a calibrated guarantee (see 16.).
Optional post-hoc temperature scaling flattens (T > 1) or sharpens (T < 1) the distribution without changing model weights; T is fitted on held-out data (see 18.).
Should you plan to implement this method in any inference engine, the following tasks need to be done:
choice, score, noul.double.kyr0/Bonsai-Llama-JevThe downloadable Markdown version contains conventional direct links for these references.
If you use the Bonsai-Llama-Jev inference engine, its method for turning causal language models into a typed-decision engine, or its Qtype-stratified temperature scaling, please cite this work:
@software{homberg2026bonsaillamajev,
author = {Homberg, Aron},
title = {Turning Causal Language Models Into Typed-Decision Engines},
year = {2026},
version = {5},
publisher = {GitHub},
url = {https://github.com/kyr0/Bonsai-Llama-Jev},
license = {MIT}
}