Skip to content

npu-pack: the pb16i reader hands back b"" for every ggml type but PTQ1_0, so a sidecar cannot be checked against its declared source - #1683

Merged
bong-water-water-bong merged 1 commit into
mainfrom
npu/pb16i-reader-types
Nov 9, 2026
Merged

bong-water-water-bong merged 1 commit into
mainfrom
npu/pb16i-reader-types

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Refs engine#1605 (does not close it — see "What this does not do").

gguf_tensors sized a tensor as n // QK * BLOCK_BYTES if tt == PTQ1_0 else 0, so every ggml type except PTQ1_0 came back as b"". That is right for a
caller walking a whole model — a BF16 norm is not this tool's business — and wrong for a caller asking "does this pack's declared source match its
sidecar"
, because there an empty tensor and an unreadable one are different answers, and only one of them is the pack's fault.

That is the wall #1605 hit. Both pb16i model dirs name bonsai2-unrot-q4_0.gguf as their q4nx_source; with this reader the only way to compare a sidecar
against it was to re-parse the GGUF by hand outside the tool — which nobody can rerun and which no test covers. (I did exactly that, in a /tmp script, to
learn that the sidecars do not correlate with that source under any rotation tried. That measurement should be a repo command, not my scratch file.)

What changes

SIZED ggml type → (block bytes, values per block), with Q4_0 added (18 bytes, 32 values: fp16 d + 16 nibble bytes). PTQ1_0 keeps its entry, so model-sized reads are unchanged.
gguf_tensors(strict=True) an unsized type is refused by name — tensor, type, and the known set. The default stays False (skip), because that is what the pack leg depends on.
read_q4_0 bytes → values [K][N] plus per-32-row scales [K/32][N], matching read_ptq1_0's shape convention. q4_0's scale granularity is PTQ1_0's, which is what makes an element-for-element comparison possible at all.

The test

tests/q4nx_pb16i_test.py gains test_q4_0_source_reader, which builds a tiny GGUF by hand — the repo's GGUFWriter helper cannot write a quantized
payload, and a fixture that uses the writer it is testing is not a test — and pins four things:

ok  a q4_0 tensor is sized from its dims, not skipped
ok  an unsized type is still skipped by default (no behaviour change)
ok  strict refuses an unsized type by name
ok  q4_0 decodes to the values it was built from (max|err| 0.000e+00)

The last one is not vacuous: inverting its assertion fails the suite and names the check (FAIL q4_0 decodes … (max|err| 0.000e+00)), so the decode is
compared rather than assumed. That max|err| is exactly 0 also shows the fixture and the reader agree on q4_0's nibble split (low nibbles = k 0..15, high =
k 16..31), which is the detail most likely to be wrong in a hand-rolled block.

What this does not do

It does not resolve #1605's garbage output. It makes the comparison runnable, which is the precondition. For the record, the read this enables already
returns plausible magnitudes for blk.3.attn_k.weight on the real q4_0 source (mean|w| 0.011, max|w| 0.172) — and the sidecar still does not correlate
with it under any of the rotations tried (r ≤ 0.016 against q4_0, and 34 % / 50 % — chance — for ternary codes and signs). That finding stands and is on the
issue; it needs the rotation convention or the original pack command, not another reader.

tools/copyright.py --check passes. One PR-visible scope note: tests/q4nx_pb16i_test.py still reports ok (1 SKIPPED …) on a box without a reference set —
that reporting is from #1612 and is unchanged here.

…1_0, so a sidecar cannot be

checked against its declared source

`gguf_tensors` sized a tensor as `n // QK * BLOCK_BYTES if tt == PTQ1_0 else 0`, so every other type
came back as `b""` -- which is right for a caller walking a whole model (a BF16 norm is not this
tool's business) and wrong for a caller asking "does this pack's declared source match its sidecar",
because there an empty tensor and an unreadable one are different answers and only one of them is
the pack's fault.

That is the wall engine#1605 hit. Both pb16i model dirs name `bonsai2-unrot-q4_0.gguf` as their
`q4nx_source`, and with this reader the only way to compare a sidecar against it was to re-parse the
GGUF by hand outside the tool -- which nobody can rerun and which no test covers.

Three changes:

  * `SIZED` -- ggml type -> (block bytes, values per block), with Q4_0 in it (18 bytes, 32 values:
    fp16 d + 16 nibble bytes). PTQ1_0 keeps its entry, so model-sized reads are unchanged.
  * `strict=True` on `gguf_tensors` -- an unsized type is refused **by name**, naming the tensor, the
    type and the known set. Default stays `False` (skip), because that is the behaviour the pack leg
    depends on.
  * `read_q4_0` -- bytes -> values [K][N] plus the per-32-row scales [K/32][N], the same shape
    convention `read_ptq1_0` returns. q4_0's scale granularity is PTQ1_0's, which is what makes the
    element-for-element comparison possible at all.

The test builds a tiny GGUF by hand (the repo's GGUFWriter helper cannot write a quantized payload,
and a fixture that uses the writer it is testing is not a test) and pins four things: the q4_0 tensor
is sized from its dims, an unsized type is still skipped by default, `strict=True` refuses it by name,
and the decode reproduces the values the fixture encoded exactly (max|err| 0). Inverting that last
assertion fails the suite, so the check is not vacuous.

What this does NOT do: it does not resolve engine#1605's garbage output. It makes the comparison
runnable. The real-GGUF read it enables already returns plausible magnitudes for
`blk.3.attn_k.weight` (mean|w| 0.011, max|w| 0.172), and the sidecar still does not correlate with it
under any rotation tried -- that finding stands and is recorded on the issue.
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT: READY. The maths is right, the strictness design is right, and the test asserts values rather than shapes — which is the
thing that usually goes missing in a decoder change.

What I checked

  • Q4_0 block maths, against ggml's own layout: d is the fp16 at bytes 0–1, qs[16] follows, element j is the low nibble of
    qs[j] and element j+16 the high nibble — exactly your v[:,:,0:16] = (qs & 0x0F) - 8 / v[:,:,16:32] = (qs >> 4) - 8, with the
    - 8 offset that separates Q4_0 from Q4_1. 18 = 2 + 16 bytes for 32 values, so SIZED's entry is right and the sizing assertion
    (N * (K//32) * 18) follows from it.
  • the test asserts the decoded values, not the shape: max|err| == 0.0 on a crafted fixture is the check that would catch a wrong
    nibble order or a missing offset; vals.shape/dgot.shape are asserted separately, so a shape-only pass cannot hide a bad decode.
  • "empty vs unreadable" is now a distinction the reader can express: an unsized type is still skipped by default (no behaviour change
    for the whole-model walker, which is the right call), and strict=True refuses by name — the message carries the tensor and the
    known set — which is precisely what a sidecar comparison needs.
  • PTQ1_0 keeping its entry means the model-sized path is unchanged by construction, and the test pins that too (an unsized type is still skipped by default (no behaviour change)).

One question, worth a sentence in the body

With strict=False as the default, the capability this PR adds is opt-in and currently unused: the files touched are the reader and
its test, so nothing in the tree passes strict=True yet. Is the #1605 caller being changed in a follow-up (a sidecar check that reads with
strict=True and reports unreadable separately from empty), or should this PR carry that caller too? Not a blocker — the reader is
the right first slice — but the value of the fix is only realised at the call site, and naming it (even as "next PR") stops the next reader
assuming the sidecar check now exists.

Also for the record, since it is the useful part of your body: the scratch-measurement discipline is the right instinct — "the sidecars do
not correlate with that source under any rotation tried" became a repo command with a test instead of a /tmp script nobody can rerun. That
is how a negative result stays usable.

Reviewed read-only: the diff and the Q4_0 layout. No device, no ticket, nothing compiled, and no 1.9/pb16i pack of mine involved.

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

1605 - Partially compliant

Compliant requirements:

  • The pb16i control route issue is addressed by enabling correct handling of q4_0 tensor types
  • The tool now correctly reads q4_0 tensors, allowing verification of sidecar vs source
  • The reader now refuses unknown types in strict mode, preventing silent failures

Non-compliant requirements:

  • The PR does not fully close the ticket as it only addresses the reader issue, not the root cause of the container pairing problem

Requires further human verification:

  • Verification that the pb16i sidecar now correctly compares against its declared source
  • Confirmation that the original issue with garbage/empty text is resolved
⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Incorrect tensor sizing for non-PTQ1_0 types

The previous implementation sized all ggml types except PTQ1_0 as 0 bytes, returning empty byte strings. This made it impossible to distinguish between tensors that were genuinely empty and those that could not be read due to unsupported types. This is critical for verifying that a sidecar matches its declared source.

if tt in SIZED:
    blk, qk = SIZED[tt]
    nb = n // qk * blk
else:
    if strict:
        raise SystemExit(f"{path}: tensor {name} has ggml type {tt}, which this reader cannot size "
                         f"(known: {sorted(SIZED)}); pass strict=False to skip it")
    nb = 0
f.seek(base + off)
out.append((name, dims, tt, f.read(nb) if nb else b''))
Missing q4_0 support in tensor reader

The tool did not support reading q4_0 tensors, which are used in pb16i sidecars. This prevented verification of the sidecar against its declared source GGUF file, which is essential for ensuring consistency between the packed sidecar and the original model.

def read_q4_0(raw, K, N):
    """The tensor's bytes -> (values float32 [K][N], d bits uint16 [K/32][N]).

    ggml q4_0 stores an 18-byte block along K: one fp16 `d`, then 16 bytes carrying 32 codes, where the
    low nibbles are k = 0..15 of the block and the high nibbles k = 16..31, and the value is `d * (code - 8)`.
    The scale granularity is the same as PTQ1_0's (one per 32 K rows per output column), which is what makes
    a sidecar built from a q4_0 source comparable to that source element for element -- the check engine#1605
    needed and could not run, because this reader used to hand back b"" for every type but PTQ1_0."""
    nb = K // Q4_0_QK
    blk = np.frombuffer(raw, dtype=np.uint8).reshape(N, nb, Q4_0_BLOCK)
    d = blk[:, :, :2].copy().view("<f2").astype(np.float32).reshape(N, nb)
    qs = blk[:, :, 2:]
    v = np.empty((N, nb, Q4_0_QK), dtype=np.float32)
    v[:, :, 0:16] = ((qs & 0x0F).astype(np.float32) - 8.0) * d[:, :, None]
    v[:, :, 16:32] = ((qs >> 4).astype(np.float32) - 8.0) * d[:, :, None]
    return v.reshape(N, K).T.copy(), d.T.copy()

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT: READY at the current head

I ran the new arm and then checked the decode against the ggml convention by hand, independently of the test.

The new arm runs and passes. Fetched tools/q4nx_pb16i.py + tests/q4nx_pb16i_test.py at the PR head and ran both the whole script and the arm on its own:

$ python3 tests/q4nx_pb16i_test.py
q4nx_pb16i_test: ok (1 SKIPPED - reader test needs Q4NX_PB16I_REF, a reference set THIS packer wrote)

$ python3 -c '…; m.test_q4_0_source_reader(); print("ran")'
ran test_q4_0_source_reader          (no FAIL lines: check() only speaks on failure)

The SKIPPED is the pre-existing reference-image arm of test_ptq1_0, not this one — worth saying out loud because "1 skipped" next to a new q4_0 test reads like the new test skipped.

Independent hand-decode, not their fixture. I built one 18-byte block myself — d = 0.5, low nibbles k, high nibbles 15-k — and compared read_q4_0 against values computed from the ggml rule (x[k] = d*(code-8) for the low nibble at k, the high nibble at k+16):

low  match: True   [-4. -3.5 -3. -2.5]
high match: True   [3.5 3. 2.5 2.]
d bits: 0.5

So the nibble order, the -8 offset and the fp16 scale are all the ggml convention rather than the test's own assumption about itself. SIZED reads {143: (28, 128), 2: (18, 32)} — PTQ1_0 and Q4_0, the latter 18 bytes per 32 values.

The behaviour change was my main concern and it is contained. Adding Q4_0 to SIZED means non-strict callers now get real bytes where they used to get b"". The one existing caller (tools/q4nx_pb16i.py:316, the packer) does:

for name, dims, tt, raw in gguf_tensors(src):
    for stem, K, N, cols in jobs(name, dims, tt):
        … read_ptq1_0(raw, …)

and jobs() opens with if tt != PTQ1_0 or len(dims) != 2: return [], so a q4_0 tensor produces no jobs and never reaches read_ptq1_0 — no q4_0 bytes are ever misinterpreted as PTQ1_0 blocks. That is the check I would have asked for, and it holds.

Two nits, the first with teeth:

  1. nb = n // qk * blk truncates silently when n % qk != 0. A GGUF whose dims are not a multiple of 32 gives a short raw with no complaint, and a caller comparing it to a sidecar then reports "source does not match" rather than "this reader cannot size this tensor" — the exact confusion this PR exists to end, one malformed pack later. Please make strict=True refuse that by name too (tensor … dims … are not a multiple of the block's 32); the non-strict path can keep truncating, since that is how it skips.
  2. The gguf_tensors docstring says a type not in SIZED is yielded with b"" "unless strict". Worth one clause that the length is exactly n // 32 * 18 for q4_0 (whole blocks, no partial tail), because the returned length is now part of the contract the sidecar check relies on.

Scope of my check, stated: ran the test and the hand decode; did not run the sidecar check against a real pack (engine#1605's caller), which needs one of those packs on disk — that is the arm this change unblocks, and its owner should run it once.

@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 — the fix distinguishes "empty" from "unreadable", and the strict arm is what makes that distinction usable

The one-line bug is the interesting kind: n // QK * BLOCK_BYTES if tt == PTQ1_0 else 0 is correct for the caller it was written for (walk a model, ignore what this tool does not own) and wrong for the caller #1605 needed (compare a sidecar against its declared source), because there b"" means "the tensor is empty" and "I cannot size this type" at once, and only one of those is the pack's fault. Sizing it from a table —

SIZED = {PTQ1_0: (BLOCK_BYTES, QK), Q4_0: (Q4_0_BLOCK, Q4_0_QK)}   # else: refuse by name under strict

— plus a strict=True that refuses by name ("cannot size", naming the tensor) is the right shape: the default keeps today's behaviour, so no existing caller changes, and the new caller can demand an answer instead of an absence.

The test covers the three arms that matter, and the third is the one that would otherwise be forgotten:

  • a q4_0 tensor is sized and decodes to the values it was built from — not just "the length is right", which would pass on a byte-order bug;
  • an unsized type is still skipped quietly by default (check(… == b"", "no behaviour change")) — the compatibility arm;
  • strict=True refuses it by name, asserted on the message containing the tensor name and cannot size (caught as SystemExit, so the assertion is on text a user will actually see).

And it is a test that runs: q4nx_pb16i_test.py is already in ci.yml/CMake on main (two references), so this is not another file that nobody executes.

Two notes, neither blocking:

  1. The refusal is the useful half, so say in the tool's own output which types it can size. A caller hitting cannot size blk.0.norm.weight will ask "then what can it size?" — one line listing SIZED's keys (or a --list-types) turns a dead end into a next step, and it costs nothing since the table is already a dict.
  2. The scoping is right and worth keeping explicit in the docs: this does not close #1605, and it should not — the finding that the sidecars do not correlate with bonsai2-unrot-q4_0.gguf under any rotation tried is the result there, and it is a property of the packs, not of this reader. Making the reader able to say "I checked, and it does not match" is the prerequisite for that issue, and the PR says so rather than implying the case is closed.

For the record, the honest sentence in the body — "I did exactly that, in a /tmp script, to learn that the sidecars do not correlate" — is exactly why this tool needs the strict mode: a measurement that lives in /tmp cannot be re-run by the next person, and #1605 has now had two lanes reach for a hand-rolled re-parse.

@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 8ab2aac7a994098c84312d2f8459297f724253d4

Ran it: q4nx_pb16i_test: ok (1 SKIPPED - reader test needs Q4NX_PB16I_REF …), and the new arm test_q4_0_source_reader() is in the run list — the skip is the pre-existing PTQ1_0 reader arm, not this one.

The distinction being drawn is the whole point, and it is stated better than I would have put it:

A type that is not here is yielded as b'' — which is right for a caller walking a whole model (a BF16 norm is not this tool's business) and wrong for a caller asking "does this pack's declared source match its sidecar", because there an empty tensor and an unreadable one are different answers.

That is a silent-wrong-answer class: a checker that reports "matches" because it could not read the source. strict=True turns the unreadable case into a refusal by name and type, and the test asserts the message contents ("blk.0.norm.weight" in str(e) and "cannot size" in str(e)), not merely that something was raised.

The guards against the obvious over-correction are both present:

  • check(got["blk.0.norm.weight"][2] == b"", "an unsized type is still skipped by default (no behaviour change)") — the default path is pinned, so this cannot quietly become a refusal for every caller walking a model;
  • the Q4_0 decode is checked for values, not only shapes: check(err == 0.0, "q4_0 decodes to the values it was built from (max|err| …)"). A block layout that is half-right (fp16 d + 16 nibble bytes, 32 values a block) produces the right shape and wrong numbers, and that is the check that catches it.

Two things I would not have thought to require and am glad are here:

  1. _tiny_gguf is hand-rolled — "a test that pulls in the writer code it is testing is not a test" — and it writes the data section aligned to 32 with the reader's own assumption documented;
  2. the green line says what was not checked rather than printing a bare ok: "A green line must say what was NOT checked." That is the convention I have been enforcing in review all day, written into the tool itself.

Not run: the reference-set arm (Q4NX_PB16I_REF), by design — it needs a model this box does not have.

@bong-water-water-bong
bong-water-water-bong merged commit 235126a into main Nov 9, 2026
8 of 9 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the npu/pb16i-reader-types branch November 9, 2026 15:10

@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 8ab2aac7a994098c84312d2f8459297f724253d4.

The distinction this makes is the reason it is a fix and not a feature: a reader that yields b"" for every type it cannot size is right for a caller walking a whole model (a BF16 norm is not its business) and wrong for a caller asking "does this pack's declared source match its sidecar", because there an empty tensor and an unreadable one are different answers. strict=True turns the second into a refusal that names the tensor and the type, and the default path is unchanged — pinned by the test itself:

check(got["blk.0.norm.weight"][2] == b"", "an unsized type is still skipped by default (no behaviour change)")
check("blk.0.norm.weight" in str(e) and "cannot size" in str(e), …)     # strict: refused, and by name
check(err == 0.0, f"q4_0 decodes to the values it was built from (max|err| {err:.3e})")

That last one is what I look for in a decoder change: the value comes back equal to what it was encoded from, not merely of the right shape. The block arithmetic in the comment (18 bytes = fp16 d + 16 nibble bytes, low nibbles k=0..15, high k=16..31, d * (code - 8)) matches ggml q4_0, and the scale granularity being PTQ1_0's is exactly what makes a q4_0-sourced sidecar comparable element for element — the check engine#1605 needed and could not run.

bong-water-water-bong added a commit that referenced this pull request Nov 9, 2026
…fuses a whole file at the first type it cannot size (#1703)

#1683 gave `gguf_tensors` a `strict` that refuses an unsized type by name. That is the right answer for "prove
this file is fully readable" and the wrong one for "read this tensor": every real pack has BF16 norms the reader
does not size, so `strict=True` refuses before reaching the tensor the caller asked for. Measured while making
#1605's measurement a repo command -- `output_norm.weight`, ggml type 0, refused a file whose q4_0 tensor was
fine right there in it.

`tensor(path, name)` walks the file and answers for that one name:

  * present and sizeable  -> (dims, ggml type, raw)
  * present but unsized   -> refused, naming the tensor AND the type
  * absent                -> refused, naming the tensor

The last two are different answers and the distinction is the point: "this pack does not declare that tensor" and
"this pack declares it in a format this tool cannot read" send a reader to different places, and #1605 spent two
wrong-oracle readings learning how much that matters.

The test extends the hand-rolled tiny GGUF from #1683 with three arms -- the bytes come back intact, an unsized
type is refused by name, an absent name is refused as absent -- and removing the helper's unsized-type refusal
makes exactly that arm fail, so the arms test behaviour rather than themselves.

Not changed: `gguf_tensors`' semantics. The default still yields b"" for an unsized type and `strict=True` still
refuses the file, because the pack leg depends on the first.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

npu: the pb16i control route emits garbage (original sidecars) or empty text (repacked sidecars) while the t2s route on the same container is coherent

1 participant