Skip to content

npu: the d3 question/answer contract, byte-equal to the pack's d3_format.py (#653) - #765

Merged
bong-water-water-bong merged 3 commits into
mainfrom
1bit/npu-systemone-contract
Nov 1, 2026
Merged

bong-water-water-bong merged 3 commits into
mainfrom
1bit/npu-systemone-contract

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

What

The d3 question/answer contract as a device-free header, checked against the pack's own d3_format.py byte for byte. This is the layer /v1/systemone will stand on: how a request's state and questions become the prompt the model reads, and how per-option probabilities become the answer object.

The pack says the model expects exactly those strings — "changing any byte changes its input" — so "close enough" is not a thing here.

npu/systemone.h

  • question_of() — a request question into keys, option texts, and the rules: choice 1–255 options (a "key: description" line, or the key alone when the description is null), noul always false/true with the pack's fallback texts ("No / false", "Yes / true"), score an ordered list of 2–10 distinct non-empty levels rendered as a choice over them.
  • user_prompt() — the State: / Question: / Options: / Reply with only the code of the best option. turn: byte-exact, including Python's ", " and ": " JSON spacing and the request's key order.
  • answer_of() — choice → {choice, probabilities, confidence}; noul → {noul}; score → {score = Σ level·p, probabilities, confidence, legend}. confidence is upstream's 1 − H/log n.
  • candidate_codes() — A..Z then AA.. up to 255.

How it is checked

tests/golden/systemone/prompts.json holds nine fixtures whose expected prompts were produced by the pack's own d3_format.user_prompt() at revision 2fc06364…, committed with that provenance in the file. They cover a null description, a JSON-object description, a JSON-array description, unicode, explicit instructions, noul with and without criteria, a bare-string state, a null state, a score over plain levels and a score over JSON levels.

ctest systemone_contract: PASS — all nine prompts byte-identical to upstream, plus the option rules (1–255, score 2–10 distinct non-empty, 255 refused at 256, noul's keys and fallbacks), the three answer shapes, ties keeping the first option (as upstream's strict > does), confidence 0 for a flat distribution and 1 for a decided one, score's expected value, and the refusals (wrong probability count, negative, all-zero).

Two things this exposed

  1. My first test draft parsed the fixtures through nlohmann::json, which sorts keys, so every JSON-description case failed. The fix is ordered_json — and the header now says why the state must stay ordered: upstream keeps the request's order, and a sorted object is a different prompt, i.e. different model input. An endpoint that ignores this would be silently wrong.
  2. score is not in d3_format.py at all. It is rendered as a choice by d3_runtime.py, which is where the expected-value answer, confidence and legend come from. The header documents that lineage rather than implying d3_format covers all three kinds.

Not in this PR

@github-actions

github-actions Bot commented Nov 1, 2026 •

Copy link
Copy Markdown

PR Reviewer Guide 🔍

(Review updated until commit 7ea2519)

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

763 - Partially compliant

Compliant requirements:

  • The npu/systemone.h header file implements the d3 question/answer contract exactly as specified
  • Tests validate the contract against golden fixtures generated by the pack's d3_format.py
  • All question types (choice, noul, score) are properly handled with validation
  • Error handling and validation for question rules and answer generation are implemented
  • The systemone_test binary is added and integrated into the build system

Non-compliant requirements:

  • The PR does not include the /v1/systemone endpoint implementation (as noted in the ticket description)
  • The PR does not include vision question support (box/track/assets) or FFmpeg integration
  • The PR does not include a real 5.14 GB d3 backbone conversion (as noted in the ticket description)

Requires further human verification:

  • Verification that the contract exactly matches the pack's d3_format.py byte for byte (though the golden fixtures provide this validation)
  • Manual verification that the implementation correctly handles all edge cases in the contract
⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Potential Precision Loss in Confidence Calculation

The confidence function in detail namespace uses double for intermediate calculations but returns a double. However, the function may lose precision when converting from float to double and back, especially when dealing with small probability values. This could lead to slightly different confidence values than expected from the Python implementation, particularly in edge cases where probabilities are very small.

inline double confidence(const std::vector<float>& p) {
    if (p.size() < 2) return 1.0;
    double entropy = 0.0;
    for (const float v : p)
        if (v > 0.0f) entropy -= double(v) * std::log(double(v));
    const double c = 1.0 - entropy / std::log(double(p.size()));
    return std::max(0.0, std::min(1.0, c));
}
Inefficient String Building in user_prompt

The user_prompt function builds the prompt string character-by-character using += operations. While this works, it could be more efficient by pre-calculating the required string size or using a std::stringstream for better performance, especially for large prompts or when called frequently in token loops.

inline std::string user_prompt(const nlohmann::ordered_json& state, const Question& q,
                               const std::vector<std::string>& codes) {
    if (codes.size() < q.texts.size())
        throw std::runtime_error("question: " + std::to_string(q.texts.size()) +
                                 " options but only " + std::to_string(codes.size()) + " answer codes");
    const bool empty = state.is_null() || (state.is_string() && state.get<std::string>().empty());
    std::string out = "State:\n";
    out += empty ? std::string(kEmptyState) : detail::describe(state);
    out += "\n\nQuestion:\n";
    out += q.instructions.empty() ? std::string(kDefaultInstructions) : q.instructions;
    out += "\n\nOptions:\n";
    for (size_t i = 0; i < q.texts.size(); i++) {
        if (i) out += "\n";
        out += codes[i] + ": " + q.texts[i];
    }
    out += "\n\n";
    out += kClosingLine;
    return out;
}

@bong-water-water-bong
bong-water-water-bong force-pushed the 1bit/npu-systemone-contract branch from d2f9226 to 68f2c9f Compare November 1, 2026 14:29
@github-actions

github-actions Bot commented Nov 1, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 68f2c9f

@bong-water-water-bong bong-water-water-bong added the tprs-ready TPRS: review verdict READY posted by the standing reviewer; merge gate satisfied label Nov 1, 2026

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: READY

At 68f2c9f3 — first review, build green. npu/systemone.h (+257), tests/systemone_test.cpp (+185), and a golden set tests/golden/systemone/prompts.json (+187, keyed source/note/cases).

Ran the test:

$ g++-16 -std=c++17 -O1 -I npu -I app -I<json-src> tests/systemone_test.cpp -lgtest -lgtest_main && ./a.out
systemone: ok        (30 checks, exit 0)

A contract PR for the d3 head, with goldens committed beside it — which is the pattern that makes a contract testable later: the prompts are data, the expectations are in the JSON, and the test drives the header against them without a device. 30 checks over a golden set is enough coverage to make a future change to the contract fail loudly rather than drift.

It is add_test()-wired, so CI runs it on every PR — for an NPU-adjacent component that is worth more than the usual green tick, since the NPU lanes themselves are not built by CI.

Not verified: the behaviour against a real d3 head on the array (the contract is exercised, the runtime is not), and the goldens' provenance — where those expected outputs came from. If they were recorded from a working run, saying so in the golden file's note would make them a regression baseline rather than an assertion of intent; if they were hand-written from the spec, that is fine too, but the difference decides what a later failure means.

tprs-ready applied.

@github-actions

github-actions Bot commented Nov 1, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit fbb82fe

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: READY

At fbb82fe6 — re-confirmed after the waiter moved the head: build green, and I re-ran the gate at this content rather than assuming the rebase was inert.

tests/systemone_test.cpp → systemone: ok, 30 checks against the committed golden set (source/note/cases), add_test()-wired so CI enforces the contract on every PR.

tprs-ready stands.

…_format.py (#653)

The /v1/systemone endpoint is only honest if its prompt is the one the model was trained on: the d3
pack's d3_format.py says the contract expects exactly those strings, and changing a byte changes the
input. This is that contract, as a device-free header, checked against the pack's own file rather than
against my reading of it.

npu/systemone.h
  question_of()    a request question -> keys, option texts, and the rules: choice 1..255 options
                   (a "key: description" line, or the key alone when the description is null), noul
                   always false/true with the pack's fallback texts, score an ordered list of 2..10
                   distinct levels rendered as a choice over them (what d3_runtime.py does)
  user_prompt()    the "State:/Question:/Options:/Reply with only the code..." turn, byte-exact --
                   including Python's ", " and ": " json spacing and the request's key order
  answer_of()      choice -> {choice, probabilities, confidence}; noul -> {noul}; score ->
                   {score = sum(level * p), probabilities, confidence, legend}
  candidate_codes() A..Z then AA.. up to 255

tests/golden/systemone/prompts.json
  Nine fixtures whose expected prompts were produced by the PACK'S d3_format.user_prompt() at revision
  2fc06364715b967f1860aea9cf38778875588b17, committed with that provenance in the file. They cover a
  null description, a JSON-object description, a JSON-array description, unicode, explicit
  instructions, noul with and without criteria, a state that is a bare string, a null state, a score
  over plain levels and a score over JSON levels.

ctest systemone_contract  PASS -- all nine prompts byte-identical to upstream, plus: the option rules
                          (1..255, score 2..10 distinct non-empty, noul's two keys and fallback texts,
                          255 refused at 256), the answer shapes, ties keeping the first option (as
                          upstream's strict > does), confidence 0 for a flat distribution and 1 for a
                          decided one, score's expected value, and the refusals (wrong count, negative,
                          all-zero)
ctest decision_head       PASS (unchanged)
ctest safetensors_to_q4nx PASS (unchanged)

Two things this exposed in my own work: the first test draft parsed the fixtures through
nlohmann::json, which sorts keys, so every JSON-description case failed -- the fix is
ordered_json, and the header now says why the state must stay ordered (upstream keeps the request's
order, and a sorted object is a different prompt). The other is that score questions are NOT in
d3_format.py at all: they are rendered as a choice by d3_runtime.py, so the header documents that
 lineage rather than implying d3_format covers them.

Not here: the HTTP route, the backbone forward + pooling and the 32,768-token per-question limit --
those are the endpoint half, on top of this contract and npu/decision.h's readout.
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

pi-prs: re-verdict at head 1f1d4bf (force-pushed from 68f2c9f).

#763 merged as dcf4751, and it adds its test registration to the same place in CMakeLists.txt, so this PR went DIRTY. Rebased as a single commit on current main; one conflict, in CMakeLists.txt, resolved by keeping both blocks — #763's decision_test (+ its add_dependencies) and this PR's systemone_test (+ its add_dependencies), each with its own comment.

Verified at this head: ctest systemone_contract, ctest decision_head and ctest npu_sampling all pass (3/3) from a clean configure, the golden fixtures still match upstream byte for byte, and tools/copyright.py --check is rc 0. Diff vs main is this PR's own 4 files: npu/systemone.h, tests/systemone_test.cpp, tests/golden/systemone/prompts.json, CMakeLists.txt (+11).

@bong-water-water-bong
bong-water-water-bong force-pushed the 1bit/npu-systemone-contract branch from fbb82fe to 1f1d4bf Compare November 1, 2026 15:22

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: READY

At 1f1d4bfb — build green after the rebase, and I re-ran the contract test at this content rather than assuming the rebase was inert: tests/systemone_test.cpp → systemone: ok (30 checks against the committed golden set).

The d3 question/answer contract remains what I reviewed: prompts as data in tests/golden/systemone/prompts.json (source/note/cases), the header driven against them without a device, and add_test()-wired so CI enforces the contract on every PR — worth more than the usual tick for an NPU-adjacent component, since the NPU lanes are not built by CI.

tprs-ready stands.

@github-actions

github-actions Bot commented Nov 1, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 449ebb1

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: READY

Confirmation at 449ebb1d: Merge branch 'main' into 1bit/npu-systemone-contract, author commit unchanged
(1f1d4bf, the one I ran the suite on), own diff still 4 files (+640), main an ancestor.

Re-ran the suite at the tip (it compiles against the newer tree now):

$ g++-16 -std=c++26 -O1 -Inpu -isystem <build>/_deps/json-src/include tests/systemone_test.cpp && ./systemone_test
systemone: ok

tprs-ready stays. No GPU and no NPU work — the test is device-free and reads a committed golden set.

@github-actions

github-actions Bot commented Nov 1, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 7ea2519

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

One contract divergence found while writing the endpoint on top of this branch, worth fixing here before merge, because the endpoint will otherwise ship it.

score answers are keyed by the level text; upstream keys them by level index.

Upstream d3_runtime.normalize_question() builds a score question as a choice whose option keys are the level
indices
, not the level texts:

return Question(kind, question, rendered,
                [str(i) for i in range(len(levels))],   # keys  -> "0", "1", "2"
                list(criteria))                          # descriptions (legend)

and product_answer() then builds the answer from those keys:

"probabilities": dict(zip(question.keys, shares)),   # {"0": p0, "1": p1, "2": p2}
"legend": {key: _canonical(text) for key, text in zip(question.keys, question.descriptions)}

answer_of() here (npu/systemone.h, the score branch) keys both by the level text instead
(probs[q.keys[i]], legend[q.keys[i]], with out.keys filled from out.texts for score). So a client that reads
probabilities or legend gets different keys than the d3 server it stands in for — {"0": …} vs {"cheap": …}.
The prompt is unaffected (it prints codes[i] + ": " + texts[i], which is why the nine golden fixtures all pass), and
score/confidence are numerically identical; it is the two dictionaries' keys that differ.

Two-line fix: give Question a separate key list for score ("0".."n-1") while keeping texts/legend as they are,
and add an assertion to ctest systemone_contract that a score answer's probabilities/legend keys are "0".."n-1"
— the fixtures predate this because they only cover the prompt.

Not changed in this branch by me right now (it is your PR, not mine to rewrite mid-review), and the endpoint PR is
stacked on this one so it cannot fix it without touching the same file. If this merges as-is I will open the small
follow-up immediately.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: READY

Confirmation at 7ea2519c: Merge branch 'main' into 1bit/npu-systemone-contract, author commit unchanged
(1f1d4bf), own diff still 4 files (+640), main an ancestor. Re-ran the suite at the tip rather than trusting the
rebase, since the tree under it moved (main now carries #761 and #764):

$ g++-16 -std=c++26 -O1 -Inpu -isystem <build>/_deps/json-src/include tests/systemone_test.cpp && ./systemone_test
systemone: ok      (rc 0)

tprs-ready stays.

@bong-water-water-bong
bong-water-water-bong merged commit 1d42bad into main Nov 1, 2026
8 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the 1bit/npu-systemone-contract branch November 1, 2026 16:22
bong-water-water-bong pushed a commit that referenced this pull request Nov 1, 2026
The route half of #653, on npu/systemone.h's contract (#765) and npu/decision.h's
readout (#763): `POST /v1/systemone` (alias `/v1/decisions`) answers `choice`/`noul`/
`score` questions about a `state`, and `GET /v1/systemone/models` lists the decision
model. When `decision_config.json` and `decision.q4nx` sit next to `model.q4nx` the
decision routes come up beside the chat ones; a pack without them is a chat model.

A decision is one backbone prefill per question, the pooled last hidden state, the
pack's readout and a temperature softmax over that question's options -- no sampling,
no grammar, no stream. To pool it, Q4nxNpuForward gains last_hidden(): the
post-final-norm vector both step() and step_batch() already compute for the LM head.

The envelope is copied from the d3 server vLLM Semantic Router already speaks
(`vllm-sr/d3-lite`'s d3_server.py at 2fc06364), not invented -- `questions` is an
object whose ids are the keys of `answers`, `usage` is {input_tokens, output_tokens: 0},
a malformed question gives 422 {"detail":{"invalid_questions":...}} and nothing runs,
and an over-limit question is a per-question `max_length_exceeded` entry with **nothing
truncated** while the other questions are still answered. That means 422 on these
routes rather than the chat route's 400; app/npu_systemone.h is device-free so the
envelope, the refusals and the prompt wrapper are tested with no model.

The prompt is the pack's chat template with enable_thinking=False, so the assistant
turn opens with an EMPTY think block: those bytes are input, and reusing chatml()
would change them.

Measured (strixhalo, Qwen3-0.6B with a SYNTHETIC 255x1024 readout -- the route is
what is under test, the choice means nothing; host GEMM under npu-hold, 0 amdxdna
errors): choice/noul/score answers, 3 questions in one request (order kept, usage
269 tokens), /v1/decisions alias, 422 unknown field / invalid_questions / images,
401 without the bearer key, and max_length_exceeded at 34086 > 32768 with the other
question answered (usage 90). ctest npu_sampling, systemone_contract, systemone_route
and decision_head pass; copyright rc 0.

Not in it, and no row claimed: a real d3-lite backbone. Its HF Qwen3_5Model pack
cannot be converted yet -- tools/safetensors_to_q4nx.py assumes 2-D tensors (the GDN
conv1d is [6144,1,4]), the pack's names are HF's (language_model.*, linear_attn.
conv1d/in_proj_*) not the engine's (model.*, ssm_conv1d/qkv_proj/...), and the GGUF on
the Hub is arch `qwen35`, which tools/gguf_to_q4nx.py does not accept. That is the
next piece, not something to fake a number for.
bong-water-water-bong added a commit that referenced this pull request Nov 1, 2026
The route half of #653, on npu/systemone.h's contract (#765) and npu/decision.h's
readout (#763): `POST /v1/systemone` (alias `/v1/decisions`) answers `choice`/`noul`/
`score` questions about a `state`, and `GET /v1/systemone/models` lists the decision
model. When `decision_config.json` and `decision.q4nx` sit next to `model.q4nx` the
decision routes come up beside the chat ones; a pack without them is a chat model.

A decision is one backbone prefill per question, the pooled last hidden state, the
pack's readout and a temperature softmax over that question's options -- no sampling,
no grammar, no stream. To pool it, Q4nxNpuForward gains last_hidden(): the
post-final-norm vector both step() and step_batch() already compute for the LM head.

The envelope is copied from the d3 server vLLM Semantic Router already speaks
(`vllm-sr/d3-lite`'s d3_server.py at 2fc06364), not invented -- `questions` is an
object whose ids are the keys of `answers`, `usage` is {input_tokens, output_tokens: 0},
a malformed question gives 422 {"detail":{"invalid_questions":...}} and nothing runs,
and an over-limit question is a per-question `max_length_exceeded` entry with **nothing
truncated** while the other questions are still answered. That means 422 on these
routes rather than the chat route's 400; app/npu_systemone.h is device-free so the
envelope, the refusals and the prompt wrapper are tested with no model.

The prompt is the pack's chat template with enable_thinking=False, so the assistant
turn opens with an EMPTY think block: those bytes are input, and reusing chatml()
would change them.

Measured (strixhalo, Qwen3-0.6B with a SYNTHETIC 255x1024 readout -- the route is
what is under test, the choice means nothing; host GEMM under npu-hold, 0 amdxdna
errors): choice/noul/score answers, 3 questions in one request (order kept, usage
269 tokens), /v1/decisions alias, 422 unknown field / invalid_questions / images,
401 without the bearer key, and max_length_exceeded at 34086 > 32768 with the other
question answered (usage 90). ctest npu_sampling, systemone_contract, systemone_route
and decision_head pass; copyright rc 0.

Not in it, and no row claimed: a real d3-lite backbone. Its HF Qwen3_5Model pack
cannot be converted yet -- tools/safetensors_to_q4nx.py assumes 2-D tensors (the GDN
conv1d is [6144,1,4]), the pack's names are HF's (language_model.*, linear_attn.
conv1d/in_proj_*) not the engine's (model.*, ssm_conv1d/qkv_proj/...), and the GGUF on
the Hub is arch `qwen35`, which tools/gguf_to_q4nx.py does not accept. That is the
next piece, not something to fake a number for.

Co-authored-by: bong-water-water-bong <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Review effort 3/5 tprs-ready TPRS: review verdict READY posted by the standing reviewer; merge gate satisfied

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant