Skip to content

tools: safetensors -> Q4NX converter + the d3 readout head loader (#653 prerequisite) - #763

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

bong-water-water-bong merged 3 commits into
mainfrom
1bit/npu-safetensors-q4nx

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

What

The conversion path #653 was blocked on, plus the readout head the /v1/systemone endpoint will sit on. Host-side, no device, no model download in the tests.

tools/gguf_to_q4nx.py (the only converter) takes GGUF; the d3 packs ship HF safetensors. That was the blocker — never the download.

Three pieces

tools/q4nx_pack.py — the q4_1 tile packers (bf16_bits/from_bf16/f16, quantize_q4_1, tiles, untile) extracted from gguf_to_q4nx.py, so both converters write with the same code and a converter with no GGUF input needs no gguf-py. gguf_to_q4nx.py now imports them; its own test still passes 14/14, which is the evidence the extraction is behaviour-preserving.

tools/safetensors_to_q4nx.py —

  • pack <hf dir> <out dir>: reads model.safetensors or the sharded files via model.safetensors.index.json, writes model.q4nx in the same container as the GGUF converter. The HF tensor names are the Q4NX names, so nothing is translated; 2-D projections become q4_1 tiles, norms/biases/the embedding stay bf16; the model's own config.json is carried over with the two Q4NX fields; tokenizer files are copied.
  • verify: every tensor against the source, dequantized (bf16 bound for bf16, relative RMS for q4_1).
  • decision: readout.safetensors + decision_config.json → decision.q4nx — one F32 [codes, hidden] matrix, kept exact, because the head is the model's decision and not a weight to quantize.

npu/decision.h — DecisionHead, the loader tensor class: logits() = W·h (one per option code), probabilities_over() = temperature softmax over the options a question offers, probabilities() = all of them. It refuses by name: a readout that is not F32, rows that do not match the declared codes, token_ids that do not line up, more than the d3 contract's 255 options, a missing readout.

Measured

check result
ctest decision_head PASS — W·h against hand values; softmax sums to 1; a 2-of-3 option subset softmaxes over itself to the hand-computed value; the readout temperature changes the distribution as exp(Δ/T) says; each refusal fires with the field named
ctest safetensors_to_q4nx PASS — synthetic single-shard and sharded HF models pack + verify; tiles decode back to the projection; the d3 head round-trips bit-exactly; unsupported dtype / mismatched code count / missing readout refused by name
real pack (vllm-sr/d3-lite, 1.04 MB readout.safetensors + decision_config.json) converts and loads: codes=255 hidden=1024 format=d3-code-readout-v1 prompt=d3 temp=1.00 base=Qwen/Qwen3.5-0.8B, 255 probabilities summing to 1.000000, a zero-mean hidden state giving 0.0040 each (1/255)
ctest npu_sampling (regression) PASS

Two bugs the tests caught in my own code

  1. Extracting f16 dropped np.ascontiguousarray, so a non-contiguous view was reinterpreted at the wrong stride — gguf_to_q4nx's exact Q4_0/Q4_1/Q4_K path went from 14/14 to 9/14 until it was restored. That is why the extraction is guarded by the existing test rather than by inspection.
  2. verify called .copy() on a bytes object.

Not in this PR

  • /v1/systemone itself — the next PR, on top of DecisionHead (endpoint, question kinds, the 32,768-token per-question limit, max_length_exceeded).
  • Vision questions (box/track/assets) and FFmpeg.
  • A real 5.14 GB d3 backbone conversion: the converter's backbone path is proven on synthetic fixtures and the real head is proven against the real pack, but downloading 5 GB is a deliberate separate step — and it would run under the 04:10 memory rule (systemd-run --user -p MemoryMax=, free -g first).

…loader class (#653)

The blocker on #653 was never the download: the d3 packs ship Hugging Face *safetensors* and the
engine's only converter, tools/gguf_to_q4nx.py, takes GGUF. This adds the missing path, host-side,
and the readout head the /v1/systemone endpoint will sit on.

tools/q4nx_pack.py
  The q4_1 tile packers that both converters write with -- bf16_bits/from_bf16/f16, quantize_q4_1,
  tiles, untile -- moved out of gguf_to_q4nx.py so the two cannot drift and so a converter with no
  GGUF input does not need gguf-py at all.  gguf_to_q4nx.py imports them; its own test still passes
  14/14, which is the proof the extraction is behaviour-preserving.

tools/safetensors_to_q4nx.py
  `pack <hf dir> <out dir>`: reads model.safetensors (or the sharded files via
  model.safetensors.index.json), writes model.q4nx in the same container as the GGUF converter --
  the HF tensor names ARE the Q4NX names, so nothing is translated -- with q4_1 tiles for 2-D
  projections and bf16 for norms, biases and the embedding, the model's own config.json plus the two
  Q4NX fields, and the tokenizer files copied.
  `verify`: every tensor against the source, dequantized (bf16 bound, q4_1 relative RMS).
  `decision`: readout.safetensors + decision_config.json -> decision.q4nx (one F32 [codes, hidden]
  matrix, kept exact: the head is the model's decision, not a weight to quantize).

npu/decision.h -- the loader tensor class
  DecisionHead loads a d3 pack's decision metadata and readout and does the arithmetic the endpoint
  needs: logits() is W*h (one per option code), probabilities_over() is the temperature softmax over
  the options a question offers, probabilities() is all of them.  It refuses what it cannot honour by
  name: a readout that is not F32, rows that do not match the declared codes, token_ids that do not
  line up, more than the d3 contract's 255 options, a missing readout.

Measured, no device and no model download in the tests:
  ctest decision_head        PASS -- synthetic packs: W*h against hand values, softmax sums to 1, a
                             subset of options softmaxes over itself (hand-computed value), the
                             readout temperature is applied, and each refusal above
  ctest safetensors_to_q4nx  PASS -- synthetic single-shard and sharded HF models pack and verify;
                             the tiles decode back to the projection; the d3 head round-trips exactly;
                             an unsupported dtype, a mismatched code count and a missing readout are
                             refused by name
  real pack, no download of the backbone: vllm-sr/d3-lite's readout.safetensors (1.04 MB) and
                             decision_config.json convert to decision.q4nx and load as
                             codes=255 hidden=1024 format=d3-code-readout-v1 prompt=d3 temp=1.00
                             base=Qwen/Qwen3.5-0.8B, with the 255 probabilities summing to 1.000000
                             (a zero-mean hidden state gives 0.0040 each, i.e. 1/255)

Two bugs the tests caught in my own code: `f16` had lost `np.ascontiguousarray` in the extraction, so a
non-contiguous view was reinterpreted at the wrong stride (gguf_to_q4nx's exact Q4_0/Q4_1/Q4_K path
went from 14/14 to 9/14 until it was restored), and `verify` called `.copy()` on a `bytes` object.

Not in this PR: /v1/systemone itself (the next one, on top of this class), the vision question kinds
(box/track/assets), and a conversion of a real 5.14 GB d3 *backbone* -- the converter's backbone path is
verified on synthetic fixtures and the real readout is verified against the real pack, but downloading
5 GB is a deliberate separate step (and would run under the memory rule).
@github-actions

github-actions Bot commented Nov 1, 2026 •

Copy link
Copy Markdown

PR Reviewer Guide 🔍

(Review updated until commit 380548c)

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

653 - Partially compliant

Compliant requirements:

  • The PR implements the d3 readout head loader (npu/decision.h) which reads decision_config.json and readout.safetensors
  • The PR includes the safetensors to Q4NX converter (tools/safetensors_to_q4nx.py) that handles d3 readout head conversion
  • The PR includes tests for both the converter and the decision head loader
  • The PR extracts q4nx packing functions into a shared module (tools/q4nx_pack.py) for consistency

Non-compliant requirements:

  • The PR does not implement the actual /v1/systemone endpoint
  • The PR does not implement the GET /v1/systemone/models endpoint
  • The PR does not implement the full decision endpoint logic including state processing and question handling
  • The PR does not implement the full vLLM Semantic Router API compatibility
  • The PR does not implement the full d3:lite model support (only the loader is implemented)

Requires further human verification:

  • The actual endpoint implementation needs to be verified
  • The full vLLM Semantic Router API compatibility needs to be verified
  • The integration with the full decision endpoint logic needs to be verified
⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Potential Memory Safety Issue

The DecisionHead::read_readout function performs a direct memory copy from file data into a vector without checking for potential integer overflow or buffer overflows. Specifically, when calculating the size of the data to read (w_.size() * 4) and when seeking to the data offset, there's no validation that these values don't exceed the maximum representable size for the underlying types, which could lead to memory corruption or undefined behavior if the file is malformed or maliciously crafted.

w_.resize(size_t(shape[0]) * size_t(shape[1]));
f.read(reinterpret_cast<char*>(w_.data()), std::streamsize(w_.size() * 4));
if (!f) throw std::runtime_error("decision: readout data is truncated");
Insecure File Handling

The tools/safetensors_to_q4nx.py script reads and writes files without proper validation of file paths or contents, which could lead to path traversal vulnerabilities or data corruption if the input files are not properly sanitized. The script also uses a fixed-size buffer for reading headers, which could be vulnerable to buffer overflows if the header length is unexpectedly large.

    n = struct.unpack("<Q", raw)[0]
    if n > 100 * 1024 * 1024:
        raise SystemExit(f"{path}: header length {n} is not plausible")
    header = json.loads(f.read(n))
return header, 8 + n
Test Coverage Limitation

The decision_test.cpp only tests the basic functionality of the DecisionHead loader, but does not test the full integration with the decision endpoint logic or the handling of edge cases like very large tensors or malformed input files. The tests also do not cover the actual HTTP API endpoints that will be used in the final implementation.

int main() {
    test_load_and_logits();
    test_temperature_and_shape_errors();
    test_missing_pieces();
    std::printf("%s\n", failures ? "FAILED" : "decision: ok");
    return failures ? 1 : 0;
}

…es instead of reporting Not Run

.github/workflows/ci.yml builds an explicit list of targets and ctest runs whatever binaries exist, so
a test whose target is missing from that list reports "Not Run" and never executes -- the comment in
the workflow says exactly that, and it is what failed this PR's first CI run (decision_head - Not Run).

The right fix is a ci.yml entry, but this lane's token has no workflow scope ('refusing to allow an
OAuth App to create or update workflow .github/workflows/ci.yml'), so the test binary is built as a
dependency of npu_sampling_test, which IS listed. Whoever can edit the workflow should add
decision_test to the list and drop this; until then the row cannot silently stop running.
@github-actions

github-actions Bot commented Nov 1, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 90f7b6a

@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 90f7b6af — first review, build green. Seven files, +982 −55: the safetensors→Q4NX converter, npu/decision.h (the "d3 head"), and their tests.

Both tests run, and both pass:

$ g++-16 -std=c++17 -O1 -I npu -I app -I<json-src> tests/decision_test.cpp -lgtest -lgtest_main && ./a.out
decision: ok
$ python3 tests/safetensors_to_q4nx_test.py
safetensors_to_q4nx: ok

So the contract header and the converter are each gated by a test that runs without a device, and both are add_test()-wired — meaning CI enforces them on every PR, unlike the NPU lanes generally. That matters more than usual here: the converter rewrites the packing of weights, and tools/gguf_to_q4nx.py loses 57 lines to tools/q4nx_pack.py, i.e. the packing logic is being centralised so the safetensors and GGUF paths cannot drift apart in how they lay out a container. Centralising it behind one tested module is the right move rather than a second copy.

Not verified: a converted container actually loading and running on the array (that is the lane's window), and the numeric fidelity of the conversion beyond what the unit test covers — for a converter the interesting failure is not "does it run" but "is the round-trip exact", so if there is a safetensors → q4nx → back comparison anywhere in the test it is worth naming in the body; if not, that is the next gate I would want.

tprs-ready applied.

@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
@github-actions

github-actions Bot commented Nov 1, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 380548c

@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 380548c7 — 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.

Both gates re-run at this head: decision: ok and safetensors_to_q4nx: ok. Packing stays centralised in tools/q4nx_pack.py, so the safetensors and GGUF paths cannot drift apart in how they lay out a container.

tprs-ready stands.

@bong-water-water-bong
bong-water-water-bong merged commit dcf4751 into main Nov 1, 2026
8 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the 1bit/npu-safetensors-q4nx branch November 1, 2026 15:10
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