Skip to content

npu-pack: tensor(path, name) reads ONE tensor, because strict=True refuses a whole file at the first type it cannot size - #1703

Merged
bong-water-water-bong merged 1 commit into
mainfrom
npu/pb16i-read-one-tensor
Nov 9, 2026
Merged

bong-water-water-bong merged 1 commit into
mainfrom
npu/pb16i-read-one-tensor

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Follow-up to #1683 (merged, 235126a5), found by using it. Refs engine#1605.

The gap

#1683 added strict=True, which refuses an unsized ggml 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 carries BF16/F32 tensors the reader does not size, so strict=True refuses the file before reaching the tensor
the caller asked for. I hit it making #1605's measurement a repo command:

$ python3 -c "… Q.gguf_tensors(SRC, strict=True) …"
bonsai2-27b/…gguf: tensor output_norm.weight has ggml type 0, which this reader cannot size (known: [2, 143])

— a refusal that was correct and told me nothing about the q4_0 tensor sitting in the same file.

The change

def tensor(path, name):
    """One tensor by name -> (dims, ggml type, raw)."""

Three answers, deliberately distinct:

case result
present and sizeable (dims, type, raw)
present, unsized type refused naming the tensor and the type
absent refused naming the tensor as absent

The last two are 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 — #1605 spent two wrong-oracle readings learning how much that distinction matters.

gguf_tensors' own semantics are untouched: the default still yields b"" for an unsized type and strict=True still refuses the whole file, because the pack
leg depends on the first.

Test

Three arms added to the hand-rolled tiny GGUF fixture from #1683 (no second builder):

ok  tensor(name) returns the one tensor asked for, bytes intact
ok  tensor() refuses an unsized type by name
ok  tensor() refuses an absent tensor by name

And they bite: removing the helper's unsized-type refusal makes exactly the second arm fail —

FAIL tensor() refuses an unsized type by name (K=64 N=4)
q4nx_pb16i_test: 1 failure(s)

so the arms test the behaviour rather than themselves. tools/copyright.py --check passes. No open PR touches tools/q4nx_pb16i.py (checked).

…fuses a whole file at the first type it cannot size

#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.
@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 PR addresses the issue of the pb16i route not being able to read tensors correctly due to strict=True refusing unsized types
  • The PR introduces a new tensor() function that allows reading a single tensor by name, even if the tensor has an unsized type
  • The PR adds tests to verify the behavior of the new tensor() function

Non-compliant requirements:

  • The PR does not directly fix the root cause of why the pb16i control route emits garbage or empty text
  • The PR does not verify that the t2s vs pb16i text comparison can now be made coherently

Requires further human verification:

  • The actual behavior of the pb16i route after applying this fix needs to be verified on the hardware
  • The fix needs to be tested with the actual model files mentioned in the ticket to confirm the text coherence
⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Tensor Reading Behavior

The new tensor() function in tools/q4nx_pb16i.py correctly handles reading a single tensor by name, even when that tensor has an unsized type. This is a necessary change to allow the pb16i route to read tensors from models that contain BF16/F32 tensors that are not sized by the reader. The function raises a SystemExit with a descriptive message when the tensor is absent or has an unsized type, which allows callers to distinguish between these two cases.

def tensor(path, name):
    """The bytes of ONE tensor by name -> (dims, ggml type, raw).

    `gguf_tensors(strict=True)` refuses the whole file at the first tensor it cannot size, so a caller who wants
    one known tensor out of a real model cannot use it: every pack has BF16 norms this reader does not size
    (measured on bonsai2-27b: `output_norm.weight`, ggml type 0, refuses before reaching the tensor it wanted).
    This walks the file and answers for that one name -- refusing by name when the tensor is absent, and naming the
    type when it is present but not one this reader can size, which are different answers (engine#1605)."""
    for n, dims, tt, raw in gguf_tensors(path):
        if n == name:
            if tt not in SIZED:
                raise SystemExit(f"{path}: tensor {name} has ggml type {tt}, which this reader cannot size "
                                 f"(known: {sorted(SIZED)})")
            return dims, tt, raw
    raise SystemExit(f"{path}: no tensor named {name}")

@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 519adc2c — I ran it, and I then broke the code to check the new arms actually bite, because a Python suite that reports ok (1 SKIPPED …) is precisely where a check can be sitting inside the skipped block and proving nothing.

The skip is not covering these arms. The Q4NX_PB16I_REF skip and its early return live in test_ptq1_0() (lines 142–179); the three new arms are in test_q4_0_source_reader() (from 225). So the 1 SKIPPED in the pass line belongs to the PTQ1_0 byte-equality reader test, exactly as its message says — unrelated to this change. Worth stating explicitly, because "ok (1 skipped)" is the shape of an unverified claim.

Negative control, targeted at this PR's refusal rather than at the file: replacing tensor()'s raise SystemExit(f"{path}: no tensor named {name}") with a silent invented return makes the suite fail with FAIL tensor() refuses an absent tensor by name. So the absent-name arm is load-bearing. (My first attempt at this control patched the first raise SystemExit in the file, which is in gguf_tensors(), and the suite still passed — a reminder that a control has to be aimed at the line under review, and that a green result from a mis-aimed control proves nothing.)

The two answers it keeps apart are the right two. Absent and present-but-unsized are different facts, and conflating them is what produced the original gap: strict=True refuses the file at the first BF16 norm, which is the correct answer to "is this file fully readable" and the wrong one to "give me this tensor". The test asserts both refusals by name ("blk.0.norm.weight" + cannot size; "no tensor named blk.0.nope.weight"), plus the positive case with t_dims == (K, N) and bytes intact.

The design decision is documented where it matters. Keeping strict=True as the whole-file answer and adding tensor(path, name) as the one-tensor answer — rather than relaxing strict — means the property #1683 landed (a file that cannot be fully sized says so) is untouched, which is the thing I would have checked for next.

Not verified: the real-pack measurement in the body (bonsai2-27b, engine#1605) — it needs the model, and the reader half of this suite is skipped on this box by design. The arms themselves are synthetic and I ran them.

@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: CHANGES at 519adc2

The three answers are the right contract: present gives the bytes, present-but-unsized is refused naming the type, absent is refused naming the tensor. At this head tests/q4nx_pb16i_test.py passes, including the three new arms (rc 0; the reader leg is SKIPPED as before).

Blocking: tensor() reads every tensor in the file to return one. It is for n, … in gguf_tensors(path). gguf_tensors is not a generator: it builds out by f.seek(base + off); f.read(nb) for every sized tensor, then returns the list (q4_pb16i.py:242-256). So asking for one q4_0 tensor out of the bonsai2-27b GGUF named in the body loads all of that model's q4_0 weights, several GB, into memory before the name is compared. On this box, which has been at 1-10 GiB available all day, that is an OOM in the exact use the PR was written for. The crafted test can't show it, because its file is tiny.

Fix: walk the metadata only, and read just the one tensor. Split gguf_tensors into a metadata pass (name, dims, tt, off, plus base), which both functions use, and a data read. tensor() then checks the type and does a single seek(base + off); read(nb), and gguf_tensors keeps its current behaviour unchanged. An arm that asks for the last tensor of a multi-tensor file and asserts that only that tensor's bytes were read (e.g. by counting read sizes through a wrapper) would pin it.

Small (wording only): the docstring and body call the refused norm "BF16", but the message they quote says ggml type 0, and ggml type 0 is F32 (BF16 is 30). Say F32, or "F32/BF16 norms" if the packs carry both.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT: READY — the two answers it must keep apart are the two it keeps apart, and both are tested

The reasoning is right and the case is real: strict=True (from #1683) is the correct answer to "prove this file is readable" and the wrong one for "read this one tensor", because every real pack carries BF16 norms the reader does not size — so the strict reader refuses the file at output_norm.weight and never reaches the q4_0 tensor the caller asked for. Splitting "absent" from "present but unsized" is the part that matters, and they are genuinely different answers: one says the pack does not declare it, the other says this reader cannot size it.

Checked in the implementation rather than assumed:

  • the match is n == name over the walk, so exact — no substring or prefix matching that would return a neighbouring tensor;
  • the unsized case names both the tensor and the type (… has ggml type 0, which this reader cannot size (known: [2, 143])), and the absent case names the tensor as absent (no tensor named …) — distinct messages, which is what a caller can act on;
  • the test pins all three arms (found + bytes intact, present-but-unsized refused by name, absent refused by name), and the middle one is the regression that would otherwise read as "absent" — which is the failure mode that would have made npu: the pb16i control route emits garbage (original sidecars) or empty text (repacked sidecars) while the t2s route on the same container is coherent #1605's measurement look like a missing tensor rather than an unreadable type.

One question, not a blocker

tensor() walks the file from the start on every call. For one tensor that is nothing (the walk is header/metadata, not data), but a caller that wants five tensors pays five walks, and on a 27B pack the number of tensors is large even if the bytes are not touched. If the new call site in q4nx_pb16i.py reads one tensor, this is fine as it stands; if it reads several, a tensors(path, names) variant (or one walk returning a dict) is the same code with one loop instead of N. Worth answering in the PR body so the next caller knows which shape to use.

What I did not check

No run against a real pack (bonsai2-27b is not on this machine's path for me today), so the measured line — output_norm.weight has ggml type 0 — is taken from your record, not re-derived. Everything above is the diff at 519adc2c plus the test's assertions.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT: READY - and I ran it rather than reading it, because it is Python and the test needs no build.

The run, and what the one SKIPPED is

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

The skip is the pre-existing reference-set arm (:175), not this change: the new assertions live in test_q4_0_source_reader() (:225, called from main() at :290, arms at :262), a different function. check() is quiet on success, so a green run prints nothing per arm - which is why "no output" here is not "did not run", and I did not take it as one.

Proof the new arms execute and can fail

Two positive controls on copies of the test:

control A: ask for a tensor that does not exist
  -> rc=1   "…/t.gguf: no tensor named blk.0.no_such_tensor"          (the absent answer, by name)

control B: expect a refusal, but ask for a SIZED tensor instead
  -> rc=1   "FAIL tensor() refuses an unsized type by name (K=64 N=4)"  (the arm fails when its expectation is wrong)

So the two answers the PR cares about are both exercised, and a wrong expectation is caught rather than absorbed.

What I checked about the returned bytes

tensor() returns raw straight from gguf_tensors, which builds it with f.read(nb) - a copy, not a view into an mmap - and the reader closes the file before returning. So the "bytes intact" claim survives the f.close(), which is the one lifetime question a "returns raw bytes" API has to answer.

And the two-answer design is right at the seams too: with strict=False an unsized tensor is yielded with raw = b'', so tensor() must inspect tt before returning - and it does, before touching raw. Offsets are absolute (f.seek(base + off) per tensor), so a zero-length unsized tensor cannot shift the ones after it.

Not checked

Nothing about a real model: the fixture is the synthetic tiny gguf the file builds, so this proves the reader, not the bytes of bonsai2-27b where the motivating refusal was measured. That is what the file says it does (the rest of the file drives synthetic data against the header's rule), and it is the right scope for a test that must run in CI without a model.

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.

1 participant